如何检测接口和抽象class之间的区别?
How to detect the difference between an interface and an abstract class?
给定以下类型:
public interface Interface { }
public abstract class Abstract { }
这是为什么:
typeof(Interface).IsAbstract == true;
注意 IsInterface
存在以检查它是否是接口:
typeof(Abstract).IsInterface == false;
来自docs:
The IsAbstract property returns true in the following cases:
The current type is abstract; that is, it cannot be instantiated, but can only serve as the base class for derived classes. In C#,
abstract classes are marked with the abstract keyword; in Visual
Basic, they are marked with the MustInherit keyword.
The current type is an interface.
所以接口被认为是抽象的,因为它不能被实例化。
如果要确定类型是抽象class,您应该执行以下操作:
typeof(YourType).IsClass && typeof(YourType).IsAbstract
给定以下类型:
public interface Interface { }
public abstract class Abstract { }
这是为什么:
typeof(Interface).IsAbstract == true;
注意 IsInterface
存在以检查它是否是接口:
typeof(Abstract).IsInterface == false;
来自docs:
The IsAbstract property returns true in the following cases:
The current type is abstract; that is, it cannot be instantiated, but can only serve as the base class for derived classes. In C#, abstract classes are marked with the abstract keyword; in Visual Basic, they are marked with the MustInherit keyword.
The current type is an interface.
所以接口被认为是抽象的,因为它不能被实例化。
如果要确定类型是抽象class,您应该执行以下操作:
typeof(YourType).IsClass && typeof(YourType).IsAbstract