class UDPClient
{
}
class LargeSimulator
{
}
class RemoteLargeSimulatorClient : UDPClient, LargeSimulator
{
}
俗话说,如果你需要多重继承,你的设计就会失效。
如何在C#中完成此操作而无需实现任何内容?
答案 0 :(得分:5)
您只能从C#中的单个基类固有。但是,您可以根据需要实现任意数量的接口。将这一事实与Extension Methods的出现相结合,你就可以解决这个问题。
答案 1 :(得分:4)
C#只允许单继承,但您可以从任意数量的接口继承。
你可以选择一个继承的类,然后创建其余的接口,或者只是将它们全部接口。
你也可以像这样链接你的遗产:
class UDPClient
{
}
class LargeSimulator : UDPClient
{
}
class RemoteLargeSimulatorClient : LargeSimulator
{
}
答案 2 :(得分:1)
要以您希望的方式获得多重继承,您需要创建UDPClient和LargeSimulator interface
而不是class
。
C#
中无法进行类多重继承答案 3 :(得分:1)
多重继承的一种可能替代品是mixins。不幸的是,C#也没有这些,但可以使用变通方法。大多数人依赖于扩展方法的使用(如之前的回答者所建议)。请参阅以下链接:
http://mortslikeus.blogspot.com/2008/01/emulating-mixins-with-c.html http://www.zorched.net/2008/01/03/implementing-mixins-with-c-extension-methods/ http://colinmackay.co.uk/blog/2008/02/24/mixins-in-c-30/
答案 4 :(得分:0)
答案简短:C#中不允许多重继承。阅读界面:http://msdn.microsoft.com/en-us/library/ms173156.aspx
稍微长一点的回答:也许其他一些设计模式适合你,比如策略模式等。继承并不是实现代码重用的唯一方法。
答案 5 :(得分:0)
interface ILARGESimulator
{
}
interface IUDPClient
{
}
class UDPClient : IUDPClient
{
}
class LargeSimulator : ILARGESimulator
{
}
class RemoteLargeSimulatorClient : IUDPClient, ILargeSimulator
{
private IUDPClient client = new UDPClient();
private ILARGESimulator simulator = new LARGESimulator();
}
不幸的是,您需要为成员编写包装器方法。 C#中的多重继承不存在。但是,您可以实现多个接口。