IsAssignableFrom, IsInstanceOfType and the is keyword, what is the difference?

前端 未结 4 704
醉梦人生
醉梦人生 2020-12-02 22:41

I have an extension method to safe casting objects, that looks like this:

public static T SafeCastAs(this object obj) {
    if (obj == null)
                


        
4条回答
  •  清歌不尽
    2020-12-02 23:02

    These functions and operators have different meaning. If you have objects you can always get types. so you do not work on what you have, but you do what needs to be done.

    When you are working with a class hierarchy differences are very clear.

    Look at following example

          class ABase
            {
    
            }
    
            class BSubclass : ABase
            {
    
            }
        ABase aBaseObj = new ABase();
                    BSubclass bSubclassObj = new BSubclass();
    
                    ABase subObjInBaseRef = new BSubclass();
    

    Different operations yield different results.

    typeof(ABase).IsInstanceOfType(aBaseObj) = True
    
    typeof(ABase).IsInstanceOfType(bSubclassObj) = True
    
    typeof(ABase).IsInstanceOfType(bSubclassObj) = True
    
    typeof(BSubclass).IsInstanceOfType(aBaseObj) = False
    
    bSubclassObj is ABase = True
    
    aBaseObj is BSubclass = False
    
    subObjInBaseRef is BSubclass = True
    
    subObjInBaseRef is BSubclass = True
    
    typeof(ABase).IsAssignableFrom(typeof(BSubclass))  = True
    
    typeof(BSubclass).IsAssignableFrom(typeof(ABase))= False
    

    In case on no hierarchy, may be everything was same. But if you work with hierarchy, IsAssignableFrom , is , and IsInstanceOfType yield different results.

    There are more possible combinations that could be tried. For example, you can introduce a class C which is not related in anyway with existing classes in this example.

提交回复
热议问题