【发布时间】:2012-05-12 00:25:15
【问题描述】:
User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
如何以这种方式测试某个变量是否属于某种类型?
【问题讨论】:
标签: c# reflection types
User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
如何以这种方式测试某个变量是否属于某种类型?
【问题讨论】:
标签: c# reflection types
GetType() 存在于每个单一的框架类型上,因为它是在基础 object 类型上定义的。所以,不管类型本身,你都可以用它来返回底层的Type
所以,你需要做的就是:
u.GetType() == t
【讨论】:
您需要查看您的实例的类型是否等于类的类型。要获取实例的类型,请使用 GetType() 方法:
u.GetType().Equals(t);
或
u.GetType.Equals(typeof(User));
应该这样做。显然,如果您愿意,可以使用 '==' 进行比较。
【讨论】:
u.GetType.Equals(typeof(User));
t 包含类型。
其他答案均存在重大遗漏。
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.
但是用反射检查 identity 来检查类型 identity,而不是 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:
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
【讨论】:
typeof(Animal).IsInstanceOfType(x) 比 typeof(Animal).IsAssignableFrom(x.GetType()); 更短更直接(如果你使用后者,Resharper 会建议使用前者)。
t 替换为typeof(Animal)。所以 Mark 改进后的形式变成了t.IsInstanceOfType(x)。
为了检查一个对象是否与给定的类型变量兼容,而不是写
u is t
你应该写
typeof(t).IsInstanceOfType(u)
【讨论】: