2009-04-16 33 views
13

我正在尝试编写一个验证来检查是否可以将一个Object实例转换为变量类型。我有一个类型的实例,他们需要提供的对象类型。但类型可能会有所不同。这基本上是我想要做的。如何判断一个实例是否属于某个类型或任何派生类型

 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派生的任何类别。

看起来像一个简单的问题,但我似乎无法弄清楚。

回答

24

如何:

 

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

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

 

这就告诉你,如果该对象可强制转换为某些类型。

+1

是的,昨天晚上我发现了。不过谢谢。 – 2009-04-16 17:40:21

7

我认为你需要重申你的条件,因为如果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 
7

如果您正在使用实例的工作,你应该去为Type.IsInstanceOfType

(返回)如果当前类型是在以O的 对象的继承层次 ,或者如果 当前类型是一个接口,它支持。假,如果这些都不 条件的情况下,或者如果o是 nullNothingnullptrnull引用 (在Visual Basic中为Nothing),或者如果 当前类型为开放式泛型类型 (即ContainsGenericParameters 返回true)。 - 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.IsAssignableFrom

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

相关问题