如何判断一个实例是某种类型或任何派生类型 [英] How to tell if an instance is of a certain Type or any derived types
问题描述
我试图写一个验证,以确认一个对象实例可以被转换为变量类型。我有一个目标,他们需要提供类型的Type实例。但类型可能会有所不同。这基本上是我想做的事情。
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 the Type can vary. This is basically what I want to do.
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方法。但我真正想检查是,如果 OBJ 是实例的典型或任何从典型派生类。
The type object itself has the IsSubClassOf, and IsInstanceOfType methods. But what I really want to check is if obj is either an instance of typ or any class derived from typ.
似乎是一个简单的问题,但我似乎无法推测出来。
Seems like a simple question, but I can't seem to figure it out.
推荐答案
这个怎么样:
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.
这篇关于如何判断一个实例是某种类型或任何派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!