假设我有一个对象,那么我怎么知道该对象是否来自特定的泛型类.例如:
public class GenericClass<T>
{
}
public bool IsDeriveFrom(object o)
{
return o.GetType().IsSubclassOf(typeof(GenericClass)); //will throw exception here
}
Run Code Online (Sandbox Code Playgroud)
请注意上面的代码会抛出异常.无法直接检索泛型类的类型,因为没有提供类型参数的泛型类没有类型.
你应该做这样的事情:
public class GenericClass<T>
{
}
public class GenericClassInherited<T> : GenericClass<T>
{
}
public static bool IsDeriveFrom(object o)
{
return o.GetType().BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>);
}
Run Code Online (Sandbox Code Playgroud)
例子:
static void Main(string[] args)
{
var generic = new GenericClassInherited<int>();
var isTrue = IsDeriveFrom(generic);
}
Run Code Online (Sandbox Code Playgroud)