C# 如何判断实例是属于特定类型还是任何派生类型
我试图编写一个验证来检查对象实例是否可以转换为变量类型。对于他们需要提供的对象类型,我有一个类型实例。但类型可能有所不同。这基本上就是我想做的C# 如何判断实例是属于特定类型还是任何派生类型,c#,casting,types,C#,Casting,Types,我试图编写一个验证来检查对象实例是否可以转换为变量类型。对于他们需要提供的对象类型,我有一个类型实例。但类型可能有所不同。这基本上就是我想做的 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 th
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是否是typ的实例,或者是从typ派生的任何类
这似乎是一个简单的问题,但我似乎想不出来。这个怎么样:
MyObject myObject = new MyObject();
Type type = myObject.GetType();
if(typeof(YourBaseObject).IsAssignableFrom(type))
{
//Do your casting.
YourBaseObject baseobject = (YourBaseObject)myObject;
}
这将告诉您该对象是否可以强制转换为该特定类型。我认为您需要重申您的条件,因为如果
obj
是派生的
的一个实例,它也将是基的一个实例。而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
如果您使用的是实例,那么应该使用
(返回)如果当前类型为
在
对象,或者如果
当前类型是一个
支持。如果两者都不是,则为false
情况就是这样,或者如果o是
nullNothingnullptra空引用
(Visual Basic中无任何内容),或者
当前类型是开放泛型类型
(即,包含通用参数
返回true)。——MSDN
如果您使用的是类型对象,那么您应该查看
(返回)如果c和当前类型为
表示相同的类型,或者
当前类型在继承中
c的层次结构,或者如果当前类型
是c实现的接口,或
如果c是泛型类型参数,并且
当前类型表示以下类型之一:
c的约束条件。如果没有,则为false
这些条件是真的,或者如果c是真的
nullNothingnullptra空引用
(Visual Basic中没有任何内容)。——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