如何检查是否变量是类型的类型的多数民众赞成存储在一个变量中 [英] How to check if variable is of type of a type thats stored within a variable

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

问题描述

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.

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

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