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

前端 未结 3 954
陌清茗
陌清茗 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 11:12

    I think you need to restate your conditions, because if obj is an instance of Derived, it will also be an instance of Base. And typ.IsIstanceOfType(obj) will return true.

    class Base { }
    class Derived : Base { }
    
    object obj = new Derived();
    Type typ = typeof(Base);
    
    type.IsInstanceOfType(obj); // = true
    type.IsAssignableFrom(obj.GetType()); // = true
    

提交回复
热议问题