C# 如何判断实例是特定类型还是任何派生类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/754858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:55:45  来源:igfitidea点击:

How to tell if an instance is of a certain Type or any derived types

c#castingtypes

提问by Eric Anastas

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.

我正在尝试编写一个验证来检查对象实例是否可以转换为变量类型。我有一个他们需要提供的对象类型的 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
        }

The type object itself has the IsSubClassOf, and IsInstanceOfType methods. But what I really want to check is if objis either an instance of typor any class derived from typ.

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

Seems like a simple question, but I can't seem to figure it out.

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

采纳答案by Hadi Eskandari

How about this:

这个怎么样:


    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.

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

回答by Samuel

I think you need to restate your conditions, because if objis an instance of Derived, it will also be an instance of Base. And typ.IsIstanceOfType(obj)will return true.

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

回答by Gishu

If you are working with Instances, you should be going for Type.IsInstanceOfType

如果您正在使用实例,则应该使用Type.IsInstanceOfType

(Returns) true if the current Type is in the inheritance hierarchy of the object represented by o, or if the current Type is an interface that o supports. false if neither of these conditions is the case, or if o is nullNothingnullptra null reference (Nothing in Visual Basic), or if the current Type is an open generic type (that is, ContainsGenericParameters returns true). -- MSDN

(返回)如果当前 Type 位于 o 表示的对象的继承层次结构中,或者当前 Type 是 o 支持的接口,则为 true。如果这两种情况都不属于这种情况,或者如果 o 为 nullNothingnullptra 空引用(在 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

If you are working with Type objects, then you should look at Type.IsAssignableFrom

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

(Returns) true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is nullNothingnullptra null reference (Nothing in Visual Basic). -- MSDN

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