更新时间: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.