Multiple Inheritance in C#

后端 未结 15 1972
醉酒成梦
醉酒成梦 2020-11-22 03:03

Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.

15条回答
  •  耶瑟儿~
    2020-11-22 03:34

    This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.

    public interface IPerson {
      int GetAge();
      string GetName();
    }
    
    public interface IGetPerson {
      IPerson GetPerson();
    }
    
    public static class IGetPersonAdditions {
      public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
        IPerson person = getPerson.GetPersion();
        return person.GetAge();
      }
      public static string GetNameViaPerson(this IGetPerson getPerson) {
        return getPerson.GetPerson().GetName();
      }
    }
    
    public class Person: IPerson, IGetPerson {
      private int Age {get;set;}
      private string Name {get;set;}
      public IPerson GetPerson() {
        return this;
      }
      public int GetAge() {  return Age; }
      public string GetName() { return Name; }
    }
    

    Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.

提交回复
热议问题