所以我在stackoverflow中看到了这个例子 通过使用接口实现多重继承。
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#中的多重继承。但是你可以实现多个接口。”
为什么我们仍然继承这两个接口?
class RemoteLargeSimulatorClient : IUDPClient, ILargeSimulator
如果你有一个has-a关系并在派生类上调用基础对象,为什么还要编写:IUDP, ILargeSimulator
?
不会简单地
class RemoteLargeSimulatorClient
{
好吗?
答案 0 :(得分:1)
如果您不在接口上创建类,则不能将其作为IUDPClient或ILargeSimulator传递给其他代码。当他说你需要手动添加实现时,他基本上建议你这样做:
interface ILargeSimulator
{
void Simulator_Method_1();
void Simulator_Method_2();
}
public class UDPClient : IUDPClient
{
public void UDPClient_Method_1() { /* do something here */ }
public void UDPClient_Method_2() { /* do something here */ }
}
interface IUDPClient
{
void UDPClient_Method_1();
void UDPClient_Method_2();
}
public class LargeSimulator : ILargeSimulator
{
public void Simulator_Method_1() { /* do something here */ }
public void Simulator_Method_2() { /* do something here */ }
}
public class RemoteLargeSimulatorClient : IUDPClient, ILargeSimulator
{
private IUDPClient client = new UDPClient();
private ILargeSimulator large = new LargeSimulator();
public void Simulator_Method_1() { this.large.Simulator_Method_1(); }
public void Simulator_Method_2() { this.large.Simulator_Method_2(); }
public void UDPClient_Method_1() { this.client.UDPClient_Method_1(); }
public void UDPClient_Method_2() { this.client.UDPClient_Method_2(); }
}
然后,您可以创建RemoteLargeSimulatorClient的对象实例,并将其用作ILargeSimulator或IUDPClient:
static void DoSomethingWithClient(IUDPClient client) { /* etc */ }
static void DoSomethingWithSimulator(ILargeSimulator simulator) { /* etc */ }
static void Main(string[] args)
{
RemoteLargeSimulatorClient foo = new RemoteLargeSimulatorClient();
DoSomethingWithClient(foo);
DoSomethingWithSimulator(foo);
}
答案 1 :(得分:0)
C#中不存在多个class
继承。否则可以从多个接口继承。您的示例是尝试解决多个类继承。
首先,您完全了解界面。 Why are interfaces useful