开发者

What is the difference between typeof and the is keyword?

开发者 https://www.devze.com 2023-04-12 19:25 出处:网络
What\'s the exact difference between the two? // When calling this method with GetByType<MyClass>()

What's the exact difference between the two?

// When calling this method with GetByType<MyClass>()

public bool GetByType<T>() {
    // this returns true:
    return typeo开发者_C百科f(T).Equals(typeof(MyClass));

    // this returns false:
    return typeof(T) is MyClass;
}


You should use is AClass on instances and not to compare types:

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

is works also with base-classes and interfaces:

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. typeof(T) is of type Type, and not of type AClass.

Check the MSDN for the is keyword and the typeof keyword


typeof(T) returns a Type instance. and the Type is never equal to 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
  • Type is not AClass and can never be since Type doesn't derive from AClass

your first statement is right


typeof returns a Type object describing T which is not of type AClass hence the is returns false.


  • first compares the two Type objects (types are themselves object in .net)
  • second, if well written (myObj is AClass) check compatibility between two types. if myObj is an instance of a class inheriting from AClass, it will return true.

typeof(T) is AClass returns false because typeof(T) is Type and AClass does not inherit from Type

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号