开发者

Can I get dynamic to work like this?

开发者 https://www.devze.com 2023-04-11 08:43 出处:网络
I have a Patient class: class Patient { public string First_Name { get; set; } public string Last_Name { get; set; }

I have a Patient class:

class Patient {
  public string First_Name { get; set; }
  public string Last_Name { get; set; }
  public DateTime Date_of_Birth { get; set; }
}

I also have an interface:

interface IPerson {
  string First_Name { get; }
  string Last_Name { get; }
}

in this console application, I would like the Display_Person method to work. It compiles but throws a run time error because Patient does not implement IPerson.

开发者_如何学运维
class Program {
  static void Main(string[] args) {
    Patient p = new Patient { 
      First_Name = "Charles", Last_Name = "Lambert",
      Date_of_Birth = new DateTime(1976,5,12),
    };
    Display_Person(p);
  }

  static void Display_Person(dynamic person) {
    IPerson p = person;
    Console.WriteLine("{0}, {1}", p.Last_Name, p.First_Name);
  }
}

What code changes, without having Patient implement the IPerson interface, can I make to get the Display_Person method to work? I would prefer a solution that is reusable.

Update: I want this to work so I can get intellisense. Please look past the triviality of this example. It short and to the point at explaining my problem. If this were 1003 loan application (when printed is the size of a book), I would not want to apply 20+ interfaces to my class so I can group related data for calculations. I also would not like having to type out all of those properties every time. The lack of intellisense has steered me away from using dynamic languages in the past. (I'm not lazy i'm efficient!)


You can use Impromptu Interface to do that.


If you really want to use dynamic, then why the conversion?

static void Display_Person(dynamic person) {
    Console.WriteLine("{0}, {1}", person.Last_Name, person.First_Name);
}

But I would still prefer if Patient implemented IPerson. It would make much more sense from a design perspective, and the type safety means any error would get caught at compile time instead of run time.


No! I don't think (without implementing IPatient) that is possible. You have to implement IPatient interface

class Patient : IPatient {}

Or remove casting.

static void Display_Person(dynamic person) 
{
    Console.WriteLine("{0}, {1}", person.Last_Name, person.First_Name);
}


IPerson is unnecessary. Just do the Display_Person like this:

static void Display_Person(dynamic person) {
    Console.WriteLine("{0}, {1}", person.Last_Name, person.First_Name);
}

So long as person implements those properties, this works fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号