如何判断实例是某个类型还是任何派生类型

Eri*_*tas 14 c# types casting

我正在尝试编写验证来检查Object实例是否可以转换为变量Type.我有一个Type实例,用于他们需要提供的对象类型.但类型可能会有所不同.这基本上就是我想要做的.

        Object obj = new object();
        Type typ = typeof(string); //just a sample, really typ is a variable

        if(obj is typ) //this is wrong "is" does not work like this
        {
            //do something
        }
Run Code Online (Sandbox Code Playgroud)

类型对象本身具有IsSubClassOf和IsInstanceOfType方法.但我真正想要检查的是objtyp的实例还是从typ派生的任何类.

看起来像一个简单的问题,但我似乎无法弄明白.

Had*_*ari 24

这个怎么样:


    MyObject myObject = new MyObject();
    Type type = myObject.GetType();

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


这告诉您该对象是否可以转换为该特定类型.


Sam*_*uel 7

我认为你需要重申你的条件,因为如果obj是一个实例Derived,它也将是一个实例Base.而typ.IsIstanceOfType(obj)将返回true.

class Base { }
class Derived : Base { }

object obj = new Derived();
Type typ = typeof(Base);

type.IsInstanceOfType(obj); // = true
type.IsAssignableFrom(obj.GetType()); // = true
Run Code Online (Sandbox Code Playgroud)


Gis*_*shu 7

如果您正在使用Instances,那么您应该使用Type.IsInstanceOfType

(返回)如果当前Type位于由o表示的对象的继承层次结构中,或者当前Type是支持的接口,则返回true.如果这两个条件都不是这样,或者如果o为nullNothingnullptra null引用(在Visual Basic中为Nothing),或者当前Type是一个开放泛型类型(即ContainsGenericParameters返回true),则返回false. - MSDN

        Base b = new Base();
        Derived d = new Derived();
        if (typeof(Base).IsInstanceOfType(b)) 
            Console.WriteLine("b can come in.");    // will be printed
        if (typeof(Base).IsInstanceOfType(d)) 
            Console.WriteLine("d can come in.");    // will be printed
Run Code Online (Sandbox Code Playgroud)

如果您正在使用Type对象,那么您应该查看Type.IsAssignableFrom

(返回)如果c和当前Type表示相同类型,或者当前Type在c的继承层次结构中,或者当前Type是c实现的接口,或者c是泛型类型参数,则返回true current Type表示c的约束之一.如果这些条件都不为真,或者如果c为nullNothingnullptra null引用(在Visual Basic中为Nothing),则返回false. - MSDN