Multiple Inheritance in C#

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

    I created a C# post-compiler that enables this kind of thing:

    using NRoles;
    
    public interface IFirst { void FirstMethod(); }
    public interface ISecond { void SecondMethod(); }
    
    public class RFirst : IFirst, Role {
      public void FirstMethod() { Console.WriteLine("First"); }
    }
    
    public class RSecond : ISecond, Role {
      public void SecondMethod() { Console.WriteLine("Second"); }
    }
    
    public class FirstAndSecond : Does, Does { }
    

    You can run the post-compiler as a Visual Studio post-build-event:

    C:\some_path\nroles-v0.1.0-bin\nutate.exe "$(TargetPath)"

    In the same assembly you use it like this:

    var fas = new FirstAndSecond();
    fas.As().FirstMethod();
    fas.As().SecondMethod();
    

    In another assembly you use it like this:

    var fas = new FirstAndSecond();
    fas.FirstMethod();
    fas.SecondMethod();
    

提交回复
热议问题