C # 's object system is a single root system, not supporting multiple inheritance of classes, only supporting multiple interface implementations, which in some ways is causing some inconvenience: we often abstract some interfaces in system design and provide an abstract class for the interface as the default implementation, and then the actual class can derive from the abstract class. If a class implements multiple interfaces, then we can only select one abstract class as the ancestor class, and then add the implementation of the other interfaces to the class manually.
This situation has changed in c#3.0, and we can now use the c#3.0 extension method to implement a "restricted multiple inheritance".
c#3.0 introduced an extension method, you can use a static class static method for a class or interface to add a method, the key is to add the method is included implementation, so we can in the c#3.0 for the interface with an implementation of the method declaration, without the need for additional implementation classes! If a class implements more than one such interface, it can achieve a similar effect of multiple inheritance.
Let's test it with code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test35
{
public interface ITestA{ }
public static class ITestAHelper
{
public static void TestA(this ITestA obj)
{
Console.WriteLine("ITestAHelper.TestA");
}
}
public interface ITestB{ }
public static class ITestBHelper
{
public static void TestB(this ITestB obj)
{
Console.WriteLine("ITestBHelper.TestB");
}
}
public class Test : ITestA, ITestB
{
}
class Program
{
static void Main(string[] args)
{
Test obj1 = new Test();
obj1.TestA();
obj1.TestB();
Console.ReadKey();
}
}
}
Results of execution:
ITestAHelper.TestA
ITestBHelper.TestB