且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否变量是类型的类型的多数民众赞成存储在一个变量中

更新时间:2023-11-29 09:47:34

其他的答案都含有显著遗漏。

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.