[C # advanced series] 12 interfaces,
C # does not support multi-inheritance of classes, but can inherit multiple interfaces. Let's just leave it simple. Let's take a look at the example below:
public interface IRead { string GetText(); } public interface IWrite { string GetText(); }
In this case, if a class inherits the two interfaces at the same time, how can we implement the methods with the same names?
Display Interface Method (EIMI)
Public class MyCpu: IRead, IWrite {string IRead. getText () {return "This method implements the IRead method";} string IWrite. getText () {return "This method implements the IWrite method";} public string GetText () {return "This method implements its own unique method ";}}
For example, you only need to add the interface name before the method. However, the display interface method can only be a private method.
However, this method should be used with caution, because after this method is used, value-type instances are boxed when converted to interfaces. Because it is private, it cannot be called by the derived class.
The most important thing is that the interface method call is amazing:
var cpu = new MyCpu();Console.WriteLine(cpu.GetText());Console.WriteLine(((IRead)cpu).GetText());IWrite b = cpu;Console.WriteLine(b.GetText());Console.ReadLine();
You must call the API one by one, which will confuse users.
Use base class or interface
- The base class is more about an identity. For example, the bird is the base class of the swallow. An interface is an action. For example, if both birds and planes can fly, flying is an interface.
- The base class can provide a good default implementation for the derived class.
- Add a method to the base class to automatically inherit the derived class. To add a method to the interface, the derived class also needs to be rewritten.
However, I think it is only good to use the first one, because it is more inclined to consider whether to use the base class or interface based on the actual business.