如何检查变量的类型是否与存储在变量中的类型匹配

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)

  • 虽然这里显示的最终方法有效,但它不必要地冗长.`typeof(Animal).IsInstanceOfType(x)`比`typeof(Animal)更简单,更直接.IsAssignableFrom(x.GetType());`(如果使用后者,Resharper会建议使用前者). (4认同)
  • 澄清:要回答原来的问题,请将“typeof(Animal)”替换为“t”。因此,Mark 的改进形式变为“t.IsInstanceOfType(x)”。 (2认同)

Dav*_*ish 13

GetType()存在于每个框架类型上,因为它是在基object类型上定义的.因此,无论类型本身如何,您都可以使用它来返回底层Type

所以,你需要做的就是:

u.GetType() == t
Run Code Online (Sandbox Code Playgroud)

  • 埃里克在下面的回答要好得多 - 请阅读. (10认同)
  • 实际上,埃里克的回答很有帮助,但并没有回答如何以原始问题中描述的“u is t”方式使用未知类型进行测试的实际问题,而您的回答确实如此。 (2认同)

Sam*_*der 9

您需要查看实例的类型是否等于类的类型.要获取实例的类型,请使用以下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)