如何检查是否变量是类型的类型的多数民众赞成存储在一个变量中
问题描述:
User u = new User();
Type t = typeof(User)
u is User -> returns true
u is t -> compilation error -
我怎么测试,如果某些变量的类型以这种方式?
how do I test if some variable is of type in this way?
答
其他的答案都含有显著遗漏。
The other answers all contain significant omissions.
的是
运营商做的不的检查操作数的运行时类型的究竟的给定类型;相反,它检查是否运行时类型的与的给定类型兼容:
The is
operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:
class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.
但检查类型的标识的与反思检查的标识的,不是的兼容性的
But checking for type identity with reflection checks for identity, not for compatibility
bool b3 = x.GetType() == typeof(Tiger); // true
bool b4 = x.GetType() == typeof(Animal); // false! even though x is an animal
如果这不是你想要的,那么你可能想IsAssignableFrom:
If that's not what you want, then you probably want IsAssignableFrom:
bool b5 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b6 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.