【问题标题】:How to tell if an instance is of a certain Type or any derived types如何判断实例是否属于某个类型或任何派生类型
【发布时间】:2009-04-16 05:34:38
【问题描述】:

我正在尝试编写验证以检查 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
        }

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

似乎是一个简单的问题,但我似乎无法弄清楚。

【问题讨论】:

    标签: c# casting types


    【解决方案1】:

    这个怎么样:

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

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

    【讨论】:

    • 是的,我昨晚发现了。不过还是谢谢。
    【解决方案2】:

    我认为你需要重申你的条件,因为如果objDerived 的一个实例,它也将是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
    

    【讨论】:

      【解决方案3】:

      如果您使用实例,您应该选择Type.IsInstanceOfType

      (返回)如果当前类型是 在继承层次结构中 由 o 表示的对象,或者如果 current Type 是一个接口 支持。如果这些都不是,则为假 条件是这种情况,或者如果 o 是 nullNothingnullptra 空引用 (在 Visual Basic 中没有),或者如果 current Type 是一个开放的泛型类型 (即 ContainsGenericParameters 返回真)。 -- 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
      

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

      (返回)如果 c 和当前类型为真 表示相同的类型,或者如果 当前类型在继承中 c 的层次结构,或者如果当前类型 是 c 实现的接口,或 如果 c 是泛型类型参数并且 当前类型代表其中之一 c的约束。如果没有,则为假 这些条件为真,或者如果 c 是 nullNothingnullptra 空引用 (在 Visual Basic 中没有)。 -- MSDN

      【讨论】:

        猜你喜欢
        • 2014-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-07
        相关资源
        最近更新 更多