[英]Multiple inheritance in C#
当我作为C#
开发人员工作时,我知道我们可以通过使用Interface
实现multiple inheritance
。
任何人都可以提供链接或代码,了解如何使用C#
实现multiple inheritance
。
我想要使用Interface
在C#
实现多重继承的代码。
提前致谢。
它不是严格的多重继承 - 但是你的C#类可以实现多个接口,这是正确的:
public class MyClass : BaseClass, IInterface1, IInterface2, IInterface3
{
// implement methods and properties for IInterface1
..
// implement methods and properties for IInterface2
..
// implement methods and properties for IInterface3
..
}
您需要为计划实现的所有接口中定义的所有方法(和属性)提供实现。
我不太清楚你在问题中寻找什么......你能澄清一下吗? 你想做什么? 你在哪里遇到麻烦?
这是一个很好的例子。
快速代码预览:
interface ICustomerCollection
{
void Add(string customerName);
void Delete(string customerName);
}
class CustomerCollection : ICustomerCollection
{
public void Add(string customerName)
{
/*Customer collection add method specific code*/
}
public void Delete(string customerName)
{
/*Customer collection delete method specific code*/
}
}
class MyUserControl: UserControl, ICustomerCollection
{
CustomerCollection _customerCollection=new CustomerCollection();
public void Add(string customerName)
{
_customerCollection.Add(customerName);
}
public void Delete(string customerName)
{
_customerCollection.Add(customerName);
}
}
实现多个接口不是多重继承的替代。 接口用于指定类将遵守的合同。 更像是抽象类。
如果要实现多重继承的效果,实现Composite Pattern可以帮助您。
class MyClass : IFirstInterface, ISecondInterface, IThirdInterface
{
// implement the methods of the interfaces
}
然后有这个从多个接口继承:
class EmptyClass : IDoSomething, IDoSomethingElse
{
}
interface IDoSomething
{
}
interface IDoSomethingElse
{
}
static class InterfaceExtensions
{
public static int DoSomething(this IDoSomething tThis)
{
return 8;
}
public static int DoSomethingElse(this IDoSomethingElse tThis)
{
return 4;
}
}
在接口上使用扩展方法,您可以拥有更多类似于多继承的东西,而不仅仅是添加接口。 由于方法不是接口定义的一部分,因此除非您愿意,否则您也不必在类中实现它们。 (并没有真正覆盖它们,您需要类型为EmptyClass的引用来调用它们,因为更具体或确切的类型名称会胜过继承类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.