![](/img/trans.png)
[英]Can't get nested IF's to work properly in C#. What am I doing wrong?
[英]Need multiple inheritance functionality in C#. What am I doing wrong?
class UDPClient
{
}
class LargeSimulator
{
}
class RemoteLargeSimulatorClient : UDPClient, LargeSimulator
{
}
俗话说,如果你需要多重继承,那么你的设计是不对的。
如何在C#中完成此操作而无需实现任何内容?
您只能从C#中的单个基类固有。 但是,您可以根据需要实现任意数量的接口。 将此事实与扩展方法的出现相结合,您就可以进行(hacky)解决方案。
C#只允许单继承,但您可以从任意数量的接口继承。
您可以只选择一个要继承的类,然后创建其余的接口,或者只创建所有接口。
你也可以像这样链接你的继承:
class UDPClient
{
}
class LargeSimulator : UDPClient
{
}
class RemoteLargeSimulatorClient : LargeSimulator
{
}
要以您希望的方式获得多重继承,您需要创建UDPClient和LargeSimulator interface
而不是class
。
C#中不可能进行类多重继承
mixin的一种可能替代是多重继承。 不幸的是,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/
简短的回答:C#中不允许多重继承。 阅读接口: http : //msdn.microsoft.com/en-us/library/ms173156.aspx
稍微长一点的回答:也许其他一些设计模式适合你,比如策略模式等。继承不是实现代码重用的唯一方法。
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#中的多重继承不存在。 但是,您可以实现多个接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.