How to check if variable's type matches Type stored in a variable

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?

143749 次浏览

GetType()存在于每个框架类型中,因为它是在基本的 object类型上定义的。因此,不管类型本身是什么,您都可以使用它来返回底层的 Type

所以,你要做的就是:

u.GetType() == t

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

或者

 u.GetType.Equals(typeof(User));

显然,如果您愿意,可以使用’= =’进行比较。

The other answers all contain significant omissions.

is操作符执行 没有检查操作数的运行时类型是否为给定类型的 没错; 相反,它检查运行时类型 与... 相容是否为给定类型:

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.

但是检查类型 身份和反射检查 身份,而不是 兼容性

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 animal

如果这不是您想要的,那么您可能需要 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

以检查对象是否与给定的类型变量兼容,而不是写入

u is t

你应该写信

typeof(t).IsInstanceOfType(u)