C# Multiple Inheritance: Techniques & Examples
In C#, a class can inherit from one or more base classes. This type of inheritance is called multiple inheritance. However, C# does not support direct multiple inheritance, meaning a class cannot directly inherit from multiple classes. Instead, a similar effect can be achieved by using interfaces. Here is one way to implement multiple inheritance:
- Define interface.
interface IBase1
{
void Method1();
}
interface IBase2
{
void Method2();
}
- Implement interface:
class DerivedClass : IBase1, IBase2
{
public void Method1()
{
// 实现 IBase1 接口的方法
}
public void Method2()
{
// 实现 IBase2 接口的方法
}
}
- Use inheritance:
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
obj.Method1();
obj.Method2();
// 可以将DerivedClass 类型的对象赋值给 IBase1 或 IBase2 类型的变量
IBase1 base1 = obj;
IBase2 base2 = obj;
base1.Method1();
base2.Method2();
}
}
By doing this, it is possible to achieve a similar effect to multiple inheritance. The class DerivedClass inherits interfaces IBase1 and IBase2, and implements the methods of these two interfaces. When using it, an object of type DerivedClass can be assigned to variables of type IBase1 or IBase2, enabling the corresponding methods to be called.