且构网

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

如何检查变量的类型是否与存储在变量中的类型匹配

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

其他答案都包含重大遗漏.

The other answers all contain significant omissions.

is 运算符检查操作数的运行时类型是否完全是给定的类型;相反,它会检查运行时类型是否给定类型兼容:

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.

但是检查类型identity,反射检查identity,而不是兼容性

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

如果这不是您想要的,那么您可能想要 IsAssignableFrom:

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A