简体   繁体   English

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

[英]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
  • typeof(T) returns a Type object typeof(T)返回一个Type对象
  • Type is not AClass and can never be since Type doesn't derive from AClass Type不是AClass,因为Type不是从AClass派生的,所以不能

your first statement is right 你的第一个陈述是对的

typeof返回Type对象描述T这是不类型的AClass因此is返回false。

  • first compares the two Type objects (types are themselves object in .net) 首先比较两个Type对象(类型本身是.net中的对象)
  • second, if well written (myObj is AClass) check compatibility between two types. 第二,如果编写得很好(myObj是AClass),请检查两种类型之间的兼容性。 if myObj is an instance of a class inheriting from AClass, it will return true. 如果myObj是继承自AClass的类的实例,则返回true。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM