How to implement multiple inheritance in C#?

In C#, a class can only directly inherit from one base class. However, multiple inheritance can be achieved using interfaces.

An interface is a contract that defines a set of methods and properties, and a class can implement one or more interfaces. By implementing multiple interfaces, a class can acquire the functionalities of multiple base classes.

Assume there are two base classes, A and B, and you want a class C to inherit the functionalities of both. You can define A and B as interfaces, and then have C implement these two interfaces. For example:

interface A
{
    void MethodA();
}

interface B
{
    void MethodB();
}

class C : A, B
{
    public void MethodA()
    {
        // 实现A的方法
    }

    public void MethodB()
    {
        // 实现B的方法
    }
}

In the example above, interface A defines a method MethodA, while interface B defines a method MethodB. Class C implements interfaces A and B, so it must implement the methods defined in both interfaces.

In this way, class C now has the capabilities of classes A and B, allowing it to utilize the MethodA and MethodB methods.

Please note that the interface only defines the signature of methods and properties, without specific implementations. Therefore, in class C, you will need to implement the concrete logic for these two methods yourself.

bannerAds