“是"- 类型运算符 [英] "is" - operator for Type
问题描述
我使用is"运算符来查找某个类:
I use the "is" operator to find a certain class:
for(int i=0; i<screens.Count; i++){
if(screen is ScreenBase){
//do something...
}
}
这很有效,尤其是当它找到从 ScreenBase 继承的任何类而不是从 ScreenBase 继承的基类时.
This works fine especially as it finds any class that inherits from the ScreenBase but not the base classes from ScreenBase.
当我只知道类型并且不想实例化类时,我想这样做:
I would like to do the same when I know only the Type and don't want to instantiate the class:
Type screenType = GetType(line);
if (screenType is ScreenBase)
但是这个比较会产生一个警告,因为它将与Type"类进行比较.
But this comparsion produces a warning as it will compare to the "Type" class.
我知道的唯一替代方法是与 ==typeof 进行比较,但这只会测试确切的类型而不是继承的类型.有没有办法获得类似于is"运算符的类似行为,但对于 Type-class 描述的类型?
The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?
推荐答案
如果您想具体了解它是否源自类型,请使用 Type.IsSubclassOf()
.这不适用于接口.
If you want to know specifically if it derives from the type, use Type.IsSubclassOf()
. This will not work for interfaces.
Type screenType = GetType(line);
if (screenType.IsSubclassOf(typeof(ScreenBase)))
{
// do stuff...
}
否则,如果您想知道该类型是否可以分配给某个类型的变量,请使用 Type.IsAssignableFrom()
.这将适用于接口.
Otherwise if you want to know if the type could be assigned to a variable of a certain type, use Type.IsAssignableFrom()
. This will work for interfaces.
Type screenType = GetType(line);
if (typeof(ScreenBase).IsAssignableFrom(screenType)) // note the usage is reversed
{
// do stuff...
}
请注意,您不一定需要类型对象来确定这一点,您可以使用 Type.IsInstanceOfType()
.它的行为或多或少类似于 IsAssignableFrom()
.
Do note that you don't necessarily need a type object to determine this, you can do this with an instance of the object using Type.IsInstanceOfType()
. It will behave more or less like IsAssignableFrom()
.
if (typeof(ScreenBase).IsInstanceOfType(line)) // note the usage is reversed
{
// do stuff...
}
这篇关于“是"- 类型运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!