2010-03-19 93 views

回答

4

如果C#这将是这样的:

public class A<T> 
{ 
} 

A<int> a = new A<int>(); 

if (a.GetType().IsGenericType && 
    a.GetType().GetGenericTypeDefinition() == typeof(A<>)) 
{ 
} 

修订

看起来这是你真正需要的是什么:

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; 
+0

?(** new object(of object)**)。GetType()。GetGenericTypeDefinition是gettype(** List **) *** True *** – serhio 2010-03-19 13:47:02

+0

引发非泛型类型的异常:?(新的ArrayList).GetType()GetGenericTypeDefinition是将gettype((名单)) **操作无效由于对象的当前状态** – serhio 2010-03-19 14:23:35

+0

是的,这是正常现象。 – 2010-03-19 14:31:37

0
Public Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type) As Boolean 
    Dim isParentGeneric As Boolean = parentType.IsGenericType 

    Return IsSubclassOf(childType, parentType, isParentGeneric) 
    End Function 

    Private Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type, ByVal isParentGeneric As Boolean) As Boolean 
    If childType Is Nothing Then 
     Return False 
    End If 

    If isParentGeneric AndAlso childType.IsGenericType Then 
     childType = childType.GetGenericTypeDefinition() 
    End If 

    If childType Is parentType Then 
     Return True 
    End If 

    Return IsSubclassOf(childType.BaseType, parentType, isParentGeneric) 
    End Function