[英]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 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
}
}
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. 您需要使用
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
}
See also How to: Examine and Instantiate Generic Types with Reflection at MSDN . 另请参阅MSDN上的如何:使用反射检查和实例化泛型类型 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.