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

45
这两者的确切区别是什么?
// 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;
}

14
警告 - 如果您需要使用继承,则此方法无法正常工作。使用 typeof(AClass).IsAssignableFrom(typeof(T)) 来解决这个问题。请参考 http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx。 - Will
@Will 谢谢你提供的信息。虽然在我的特定情况下无关紧要,但了解这些信息很好! - Dennis Traub
6个回答

61

应该在实例上使用is AClass而不是比较类型:

var myInstance = new AClass();
var isit = myInstance is AClass; //true

is关键字也适用于基类和接口:

MemoryStream stream = new MemoryStream();

bool isStream = stream is Stream; //true
bool isIDispo = stream is IDisposable; //true

2
谢谢。解释简洁明了,内容全面。 - Dennis Traub

33
is 关键字用于检查一个对象是否属于某个类型。而 typeof(T)Type 类型的,而不是 AClass 类型的。
请参考 MSDN 上有关 is 关键字typeof 关键字 的信息。

很遗憾我只能接受一个。我能做的最好的就是给其他人点赞。谢谢! - Dennis Traub

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

很遗憾我只能接受一个。我能做的最好的就是给其他人点赞。谢谢! - Dennis Traub

11
  • typeof(T) 返回一个 Type 对象
  • Type 不是 AClass,也永远不可能是 AClass,因为 Type 没有从 AClass 派生

你的第一个陈述是正确的


很遗憾我只能接受一个。我能做的最好的就是给其他人点赞。谢谢! - Dennis Traub

10

typeof 返回一个描述 TType 对象,但它不是 AClass 类型,因此 is 返回 false。


很遗憾我只能接受一个。我能做的最好的就是给其他人点赞。谢谢! - Dennis Traub

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

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


3
很遗憾,我只能接受一个。我所能做的就是给其他人点赞。谢谢! - Dennis Traub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接