Den*_*aub 42 c# generics types
这两者之间的确切区别是什么?
// 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;
}
Run Code Online (Sandbox Code Playgroud)
gsh*_*arp 59
您应该is AClass在实例上使用而不是比较类型:
var myInstance = new AClass();
var isit = myInstance is AClass; //true
Run Code Online (Sandbox Code Playgroud)
is 也适用于基类和接口:
MemoryStream stream = new MemoryStream();
bool isStream = stream is Stream; //true
bool isIDispo = stream is IDisposable; //true
Run Code Online (Sandbox Code Playgroud)
jav*_*iry 25
typeof(T)返回一个Type实例.而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
Run Code Online (Sandbox Code Playgroud)
Vde*_*edT 10
typeof(T)是AClass返回false,因为typeof(T)是Type而AClass不从Type继承