如何检查variables的types是否匹配存储在variables中的types
User u = new User(); Type t = typeof(User); u is User -> returns true u is t -> compilation error 如何testing某些variables是否属于某种types?
其他答案都包含重大遗漏。
  is运算符不检查操作数的运行时types是否完全是给定的types; 而是检查运行时types是否与给定types兼容 : 
 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. 
但是使用reflection来检查types标识将检查身份 ,而不是为了兼容性
 bool b3 = x.GetType() == typeof(Tiger); // true bool b4 = x.GetType() == typeof(Animal); // false! even though x is an animal 
如果这不是你想要的,那么你可能想要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. 
  GetType()存在于每个框架types中,因为它是在基础objecttypes上定义的。 所以,无论types本身如何,您都可以使用它来返回基础Type 
所以,你需要做的是:
 u.GetType() == t 
 您需要查看您的实例的types是否等于类的types。 要获取使用GetType()方法的实例的types: 
  u.GetType().Equals(t); 
要么
  u.GetType.Equals(typeof(User)); 
应该这样做。 如果你愿意,显然你可以用'=='来进行比较。
为了检查一个对象是否与给定的typesvariables兼容,而不是写入
 u is t 
你应该写
 typeof(t).IsInstanceOfType(u)