Interface vs Base class

后端 未结 30 3091
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  半阙折子戏
    2020-11-21 07:58

    The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:

    Base Classes vs. Interfaces An interface type is a partial description of a value, potentially supported by many object types. Use base classes instead of interfaces whenever possible. From a versioning perspective, classes are more flexible than interfaces. With a class, you can ship Version 1.0 and then in Version 2.0 add a new method to the class. As long as the method is not abstract, any existing derived classes continue to function unchanged.

    Because interfaces do not support implementation inheritance, the pattern that applies to classes does not apply to interfaces. Adding a method to an interface is equivalent to adding an abstract method to a base class; any class that implements the interface will break because the class does not implement the new method. Interfaces are appropriate in the following situations:

    1. Several unrelated classes want to support the protocol.
    2. These classes already have established base classes (for example, some are user interface (UI) controls, and some are XML Web services).
    3. Aggregation is not appropriate or practicable. In all other situations, class inheritance is a better model.

提交回复
热议问题