C#中的多重继承

nun*_*unu 6 c# oop inheritance multiple-inheritance

当我作为C#开发人员工作时,我知道我们可以multiple inheritance通过使用来实现Interface.

任何人都可以请我提供链接或代码,如何实现multiple inheritanceC#.

我希望代码如何C#在使用中实现多重继承Interface.

提前致谢.

mar*_*c_s 12

它不是严格的多重继承 - 但是你的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
   ..
}
Run Code Online (Sandbox Code Playgroud)

您需要为计划实现的所有接口中定义的所有方法(和属性)提供实现.

我不太清楚你在问题中寻找什么......你能澄清一下吗?你想做什么?你在哪里遇到麻烦?

  • 你**不能**实现接口完全相同的行为,就像你真正的多重继承一样.接口只定义一个功能接口 - 您不能从多个实现继承.这是一个近似值 - 不是一个确切的替代品. (7认同)

mr.*_*r.b 7

这是一个很好的例子.

http://blog.vuscode.com/malovicn/archive/2006/10/20/How-to-do-multiple-inheritance-in-C_2300_- 2D00 -Implementation-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);
      }
}
Run Code Online (Sandbox Code Playgroud)


Hem*_*ant 7

实现多个接口不是多重继承的替代.接口用于指定类将遵守的合同.更像是抽象类.

如果要实现多重继承的效果,实现Composite Pattern可以帮助您.