[英]C# Multiple Inheritance with Interfaces
public interface IA
{
void DoSomething();
void Calculate();
}
public interface IB
{
void DoSomethingElse();
void Calculate();
}
public class A : IA
{
void DoSomething() { }
void Calculate() {}
}
public class B : IB
{
void DoSomethingElse() { }
void Calculate() {}
}
public class C : IA, IB
{
//How can I implement Calculate() in class B and DoSomething() in class A?
}
How can I avoid duplicate code in class C. Reference: How to simulate multiple inheritance in C# . 如何在C类中避免重复的代码。参考: 如何在C#中模拟多重继承 。 I don't want to write the full methods again in class C. Thanks for any help. 我不想在C级再次编写完整的方法。感谢您的帮助。
Note that you are not achieving multiple inheritance at all. 请注意,您根本没有实现多重继承。 C# has singular inheritance. C#具有单一的继承性。 You are implementing multiple interfaces. 您正在实现多个接口。
There is absolutely no reason why you cannot implement the interfaces in classes A
and B
, and then have B
derive from A
and C
derive from B. The method implementations from the interfaces can even be abstract, which forces the child class to do the implementation. 绝对没有理由不能在A
和B
类中实现接口,然后B
从A
派生而C
从B派生。接口的方法实现甚至可以是抽象的,这迫使子类执行实现。 If you follow this approach then you can still pass C
around as IA
or IB
simply by casting or using the as
keyword. 如果您遵循这种方法,那么您仍然可以通过强制转换或使用as
关键字将C
传递为IA
或IB
。
You can also have interface IB
"inherit" 1 (implement) IA
, which means anything that implements IB
must also implement IA
. 您还可以使用接口IB
“继承” 1 (实现) IA
,这意味着实现IB
任何东西也必须实现IA
。
1 When IB
derives from IA
it isn't inheritance like it is at the class level, it is actually still implementation. 1当IB
派生自IA
它不像在类级别那样继承,它实际上仍然是实现。 So IB
implements IA
, it doesn't inherit it. 因此IB
实现 IA
,它不会继承它。
Assuming that IA.Calculate()
is not the same as IB.Calculate()
and you therefore can't just make IB
inherit from IA
, you can implement both interfaces in C
by delegating execution on private instances of A
and B
: 假设IA.Calculate()
是不一样的IB.Calculate()
你因此不能只是做IB
继承IA
,可以实现在两个接口C
通过委派上的私人情况下执行A
和B
:
public class C : IA, IB
{
private A _a;
private B _b;
public C()
{
this._a = new A();
this._b = new B();
}
public void DoSomething()
{
this._a.DoSomething();
}
void IA.Calculate()
{
this._a.Calculate();
}
public void DoSomethingElse()
{
this._b.DoSomethingElse();
}
void IB.Calculate()
{
this._b.Calculate();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.