[英]What is the difference between typeof and the is keyword?
What's the exact difference between the two? 这两者之间的确切区别是什么?
// When calling this method with GetByType<MyClass>()
public bool GetByType<T>() {
// this returns true:
return typeof(T).Equals(typeof(MyClass));
// this returns false:
return typeof(T) is MyClass;
}
You should use is AClass
on instances and not to compare types: 您应该在实例上使用
is AClass
而不是比较类型:
var myInstance = new AClass();
var isit = myInstance is AClass; //true
is
works also with base-classes and interfaces: is
适用于基类和接口:
MemoryStream stream = new MemoryStream();
bool isStream = stream is Stream; //true
bool isIDispo = stream is IDisposable; //true
The is
keyword checks if an object is of a certain type. is
关键字检查对象是否属于某种类型。 typeof(T)
is of type Type
, and not of type AClass
. typeof(T)
的类型为Type
,而不是AClass
类型。
Check the MSDN for the is keyword and the typeof keyword 检查MSDN的is关键字和typeof关键字
typeof(T)
returns a Type
instance. typeof(T)
返回一个Type
实例。 and the Type
is never equal to AClass
并且
Type
永远不会等于AClass
var t1 = typeof(AClass)); // t1 is a "Type" object
var t2 = new AClass(); // t2 is a "AClass" object
t2 is AClass; // true
t1 is AClass; // false, because of t1 is a "Type" instance, not a "AClass" instance
your first statement is right 你的第一个陈述是对的
typeof
返回Type
对象描述T
这是不类型的AClass
因此is
返回false。
typeof(T) is AClass returns false because typeof(T) is Type and AClass does not inherit from Type typeof(T)是AClass返回false,因为typeof(T)是Type而AClass不从Type继承
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.