C#中的多重inheritance
当我作为C#
开发人员工作时,我知道我们可以通过使用Interface
实现multiple inheritance
。
任何人都可以提供链接或代码,了解如何使用C#
实现multiple inheritance
。
我想要使用Interface
在C#
实现多重inheritance的代码。
提前致谢。
这是一个很好的例子。
http://blog.vuscode.com/malovicn/archive/2006/10/20/How-to-do-multiple-inheritance-in-C_2300_- 2D00 -Inmplementation-over-delegation-_2800_IOD_2900_.aspx
快速代码预览:
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); } }
它不是严格的多重inheritance – 但是你的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 .. }
您需要为计划实现的所有接口中定义的所有方法(和属性)提供实现。
我不太清楚你在问题中寻找什么……你能澄清一下吗? 你想做什么? 你在哪里遇到麻烦?
实现多个接口不是多重inheritance的替代。 接口用于指定类将遵守的合同。 更像是抽象类。
如果要实现多重inheritance的效果,实现Composite Pattern可以帮助您。
class MyClass : IFirstInterface, ISecondInterface, IThirdInterface { // implement the methods of the interfaces }
然后有这个从多个接口inheritance:
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; } }
在接口上使用扩展方法,您可以拥有更多类似于多inheritance的东西,而不仅仅是添加接口。 由于方法不是接口定义的一部分,因此除非您愿意,否则您也不必在类中实现它们。 (并没有真正覆盖它们,您需要类型为EmptyClass的引用来调用它们,因为更具体或确切的类型名称会胜过inheritance类型。