typeof和is关键字有什么区别?

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)

  • 谢谢.很好,简短而全面的解释. (2认同)

Jen*_*ens 33

is关键字的检查对象是否是特定类型的.typeof(T)是类型Type,而不是类型AClass.

检查MSDN的is关键字typeof关键字


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)


Muh*_*han 11

  • typeof(T)返回一个Type对象
  • Type不是AClass,因为Type不是从AClass派生的,所以不能

你的第一个陈述是对的


Joe*_*oey 10

typeof返回一个Type描述T哪个不是类型的对象,AClass因此is返回false.


Vde*_*edT 10

  • 首先比较两个Type对象(类型本身是.net中的对象)
  • 第二,如果写得好(myObj是AClass),检查两种类型之间的兼容性.如果myObj是继承自AClass的类的实例,则返回true.

typeof(T)是AClass返回false,因为typeof(T)是Type而AClass不从Type继承

  • 不幸的是我只接受一个.我能做的最少就是赞成其他人.谢谢! (3认同)