要检查类型是否是C#中另一种类型的子类,很容易:
typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true
Run Code Online (Sandbox Code Playgroud)
但是,这将失败:
typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false
Run Code Online (Sandbox Code Playgroud)
有没有办法检查类型是否是基类本身的子类OR,而不使用OR运算符或使用扩展方法?
用它来检查是否c是实例TForm.
c.GetType().Name.CompareTo("TForm") == 0
Run Code Online (Sandbox Code Playgroud)
除了使用stringas作为参数之外,还有更安全的类型CompareTo()吗?
假设我有一个看起来像这样的类:
class Derived : // some inheritance stuff here
{
}
Run Code Online (Sandbox Code Playgroud)
我想在我的代码中检查这样的内容:
Derived is SomeType;
Run Code Online (Sandbox Code Playgroud)
但看起来像is运算符需要Derived是Dervied类型的变量,而不是Derived本身.我不想创建Derived类型的对象.
如何在SomeType不实例化的情况下确保Derived继承?
PS如果它有帮助,我想要一些where关键字与泛型有关的东西.
编辑:
类似于这个答案,但它正在检查一个对象.我想查看课程本身.