我怎样才能识别一个泛型类? [英] How can I recognize a generic class?
本文介绍了我怎样才能识别一个泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何能识别(.NET 2 )泛型类?
How can I recognize (.NET 2) a generic class?
Class A(Of T)
End Class
' not work '
If TypeOf myObject Is A Then
推荐答案
如果C#这将是这样的:
If c# it would be like this:
public class A<T>
{
}
A<int> a = new A<int>();
if (a.GetType().IsGenericType &&
a.GetType().GetGenericTypeDefinition() == typeof(A<>))
{
}
更新时间:
看起来这是你真正需要的:
It looks like this is what you really needed:
public static bool IsSubclassOf(Type childType, Type parentType)
{
bool isParentGeneric = parentType.IsGenericType;
return IsSubclassOf(childType, parentType, isParentGeneric);
}
private static bool IsSubclassOf(Type childType, Type parentType, bool isParentGeneric)
{
if (childType == null)
{
return false;
}
childType = isParentGeneric && childType.IsGenericType ? childType.GetGenericTypeDefinition() : childType;
if (childType == parentType)
{
return true;
}
return IsSubclassOf(childType.BaseType, parentType, isParentGeneric);
}
和可以是这样的:
public class A<T>
{
}
public class B : A<int>
{
}
B b = new B();
bool isSubclass = IsSubclassOf(b.GetType(), typeof (A<>)); // returns true;
这篇关于我怎样才能识别一个泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文