如何检查变量的类型是否与变量中存储的类型匹配
本文关键字:类型 变量 存储 是否 何检查 检查 | 更新日期: 2023-09-27 18:32:51
User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
如何以这种方式测试某个变量是否属于某种类型?
其他答案都包含重大遗漏。
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 variable "Type t" from the question:
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 variable "Type t" from the question:
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true
GetType()
存在于每个框架类型上,因为它是在基object
类型上定义的。因此,无论类型本身如何,都可以使用它来返回基础Type
因此,您需要做的就是:
u.GetType() == t
您需要查看实例的 Type 是否等于类的类型。 若要获取实例的类型,请使用 GetType()
方法:
u.GetType().Equals(t);
或
u.GetType.Equals(typeof(User));
应该这样做。 显然,如果您愿意,可以使用"=="进行比较。
为了检查对象是否与给定的类型变量兼容,而不是写入
u is t
你应该写
typeof(t).IsInstanceOfType(u)