相关疑难解决方法(0)

C#中的多重继承

由于多重继承是不好的(它使源更复杂),C#不直接提供这样的模式.但有时候拥有这种能力会有所帮助.

例如,我能够使用接口和三个类来实现缺少的多继承模式:

public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }

public class First:IFirst 
{ 
    public void FirstMethod() { Console.WriteLine("First"); } 
}

public class Second:ISecond 
{ 
    public void SecondMethod() { Console.WriteLine("Second"); } 
}

public class FirstAndSecond: IFirst, ISecond
{
    First first = new First();
    Second second = new Second();
    public void FirstMethod() { first.FirstMethod(); }
    public void SecondMethod() { second.SecondMethod(); }
}
Run Code Online (Sandbox Code Playgroud)

每次我向其中一个接口添加方法时,我都需要更改类FirstAndSecond.

有没有办法将多个现有类注入一个新类,就像在C++中一样?

也许有一种使用某种代码生成的解决方案?

或者它可能看起来像这样(假想的c#语法):

public class FirstAndSecond: IFirst from First, ISecond …
Run Code Online (Sandbox Code Playgroud)

c# interface multiple-inheritance

207
推荐指数
5
解决办法
37万
查看次数

是否可以在C#中实现mixins?

我听说有可能使用扩展方法,但我自己也无法弄明白.如果可能的话,我想看一个具体的例子.

谢谢!

c# extension-methods mixins

56
推荐指数
3
解决办法
3万
查看次数