确定对象是否为Generic

时间:2011-07-26 12:19:50

标签: c# generics

我编写了以下代码,我试图确定泛型类类型是否继承自基类。我认为这更容易解释我在代码中做了什么。有人可以提供一些有关如何解决这个问题的见解。

public class MyGeneric<T>
{
}

public class MyBaseClass
{
}

public class MyClass1 : MyBaseClass
{
}

static void Main(string[] args)
{
    MyGeneric<MyClass1> myList = new MyGeneric<MyClass1>();

    if(myList.GetType() == typeof(MyGeneric<>))
    {
        // Not equal
    }

    // This is the test I would like to pass!
    if(myList.GetType() == typeof(MyGeneric<MyBaseClass>))
    {
        // Not equal
    }

    if(myList.GetType() == typeof(MyGeneric<MyClass1>))
    {
        // Equal
    }
}

1 个答案:

答案 0 :(得分:5)

您需要使用Type.GetGenericArguments来获取泛型参数的数组,然后检查它们是否属于同一层次结构。

MyGeneric<MyClass1> myList = new MyGeneric<MyClass1>();

if(myList.GetType() == typeof(MyGeneric<>))
{
    // Not equal
}

// WARNING: DO NOT USE THIS CODE AS-IS!
//   - There are no error checks at all
//   - It should be checking that myList.GetType() is a constructed generic type
//   - It should be checking that the generic type definitions are the same
//     (does not because in this specific example they will be)
//   - The IsAssignableFrom check might not fit your requirements 100%
var args = myList.GetType().GetGenericArguments();
if (typeof(MyBaseClass).IsAssignableFrom(args.Single()))
{
    // This test should succeed
}

另见How to: Examine and Instantiate Generic Types with Reflection at MSDN