Multiple Inheritance in C#

后端 未结 15 1835
醉酒成梦
醉酒成梦 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:08

    If you can live with the restriction that the methods of IFirst and ISecond must only interact with the contract of IFirst and ISecond (like in your example)... you can do what you ask with extension methods. In practice, this is rarely the case.

    public interface IFirst {}
    public interface ISecond {}
    
    public class FirstAndSecond : IFirst, ISecond
    {
    }
    
    public static MultipleInheritenceExtensions
    {
      public static void First(this IFirst theFirst)
      {
        Console.WriteLine("First");
      }
    
      public static void Second(this ISecond theSecond)
      {
        Console.WriteLine("Second");
      }
    }
    

    ///

    public void Test()
    {
      FirstAndSecond fas = new FirstAndSecond();
      fas.First();
      fas.Second();
    }
    

    So the basic idea is that you define the required implementation in the interfaces... this required stuff should support the flexible implementation in the extension methods. Anytime you need to "add methods to the interface" instead you add an extension method.

提交回复
热议问题