In C# what is the equivalent of “is” keyword but using Type objects

后端 未结 3 1419
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 06:00

An easy question I guess, but in the documentation of the Type class they only talk of interfaces on the GetInterfaces method.

i.e. typeof(ChildClass).XXX(typeof(Par

相关标签:
3条回答
  • 2021-01-06 06:16

    I suggest you search for an equivalent. Instead of using the "is" keyword like this:

    if (object is class)
    { ... }
    

    you could simply compare the types of those two like this:

    if( typeof(object) == typeof(class)
    { ... }
    

    BUT: this is not the same, the "is" keyword can determine if the object-class is of the specified class, an inheritence of that class, implements the interface, etc, whereas the typeof() equivalence just compares the actual type.

    0 讨论(0)
  • 2021-01-06 06:26

    typeof(ParentClass).IsAssignableFrom(typeof(ChildClass))

    0 讨论(0)
  • 2021-01-06 06:32

    It depends on what you need; IsAssignableFrom, perhaps:

    bool stringIsObj = typeof(object).IsAssignableFrom(typeof(string));
    

    or IsSubclassOf:

    bool stringIsObj = typeof(string).IsSubclassOf(typeof(object));
    
    0 讨论(0)
提交回复
热议问题