如何检查变量的类型是否与存储在变量中的类型匹配 [英] How to check if variable's type matches Type stored in a variable

查看:14
本文介绍了如何检查变量的类型是否与存储在变量中的类型匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 some type in this way?

推荐答案

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

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 

这篇关于如何检查变量的类型是否与存储在变量中的类型匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆