Kar*_*ran 89 c# reflection types
User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
Run Code Online (Sandbox Code Playgroud)
如何以这种方式测试某个变量是否属于某种类型?
Eri*_*ert 188
其他答案都包含重大遗漏.
在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.
Run Code Online (Sandbox Code Playgroud)
但是通过反射检查类型标识是否检查身份,而不是兼容性
bool b3 = x.GetType() == typeof(Tiger); // true
bool b4 = x.GetType() == typeof(Animal); // false! even though x is an animal
Run Code Online (Sandbox Code Playgroud)
如果这不是你想要的,那么你可能想要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.
Run Code Online (Sandbox Code Playgroud)
Dav*_*ish 13
GetType()存在于每个框架类型上,因为它是在基object类型上定义的.因此,无论类型本身如何,您都可以使用它来返回底层Type
所以,你需要做的就是:
u.GetType() == t
Run Code Online (Sandbox Code Playgroud)
您需要查看实例的类型是否等于类的类型.要获取实例的类型,请使用以下GetType()方法:
u.GetType().Equals(t);
Run Code Online (Sandbox Code Playgroud)
要么
u.GetType.Equals(typeof(User));
Run Code Online (Sandbox Code Playgroud)
应该这样做.显然,如果您愿意,可以使用'=='进行比较.
小智 5
为了检查对象是否与给定类型变量兼容,而不是编写
u is t
Run Code Online (Sandbox Code Playgroud)
你应该写
typeof(t).IsInstanceOfType(u)
Run Code Online (Sandbox Code Playgroud)