What is the difference between typeof and the is keyword?

前端 未结 6 1042
太阳男子
太阳男子 2021-01-03 19:11

What\'s the exact difference between the two?

// When calling this method with GetByType()

public bool GetByType() {
    // this ret         


        
相关标签:
6条回答
  • 2021-01-03 19:49

    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
    
    0 讨论(0)
  • 2021-01-03 19:51

    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
    
    0 讨论(0)
  • 2021-01-03 19:55

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

    0 讨论(0)
  • 2021-01-03 19:57

    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

    0 讨论(0)
  • 2021-01-03 19:59
    • 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

    0 讨论(0)
  • 2021-01-03 20:04
    • 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 讨论(0)
提交回复
热议问题