我怎样才能识别一个泛型类?泛型类

2023-09-04 00:50:35 作者:並不都是微笑

我如何能识别(.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;