开发者

Determine whether object is a Generic

I have written the following code where I am trying to determine whether a generic classes type inherits from a base class. I think this is easier to explain what I am doing in code. Could anybody please provide some insight into how to get around this issue.

public class MyGeneric<T>
{
}

public class MyBaseClass
{
}

public class MyClass1 : MyBaseClass
{
}

static void Main(string[] args)
{
    MyGeneric<MyClass1> myList = new MyGener开发者_StackOverflowic<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
    }
}


You need to use Type.GetGenericArguments to get an array of the generic arguments, and then check if they are part of the same hierarchy.

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
}

See also How to: Examine and Instantiate Generic Types with Reflection at MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜