How to tell if an instance is of a certain Type or any derived types

前端 未结 3 911
陌清茗
陌清茗 2021-01-17 10:06

I\'m trying to write a validation to check that an Object instance can be cast to a variable Type. I have a Type instance for the type of object they need to provide. But th

3条回答
  •  北海茫月
    2021-01-17 10:51

    How about this:

    
        MyObject myObject = new MyObject();
        Type type = myObject.GetType();
    
        if(typeof(YourBaseObject).IsAssignableFrom(type))
        {  
           //Do your casting.
           YourBaseObject baseobject = (YourBaseObject)myObject;
        }  
    
    
    

    This tells you if that object can be casted to that certain type.

提交回复
热议问题