2010-03-19 6 views

Répondre

4

Si C# ce serait comme ceci:

public class A<T> 
{ 
} 

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

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

MISE À JOUR:

On dirait que c'est ce que vous avez vraiment besoin:

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); 
} 

et peut être utilisé comme celui-ci :

public class A<T> 
{ 
} 

public class B : A<int> 
{ 

} 

B b = new B(); 
bool isSubclass = IsSubclassOf(b.GetType(), typeof (A<>)); // returns true; 
+0

? (** nouvelle liste (d'objet) **). GetType(). GetGenericTypeDefinition est gettype (** Liste (de) **) *** vrai *** – serhio

+0

throws Exception pour les types non génériques :? (new ArrayList) .GetType(). GetGenericTypeDefinition is gettype (Liste (de)) ** L'opération n'est pas valide en raison de l'état actuel de l'objet. ** – serhio

+0

Oui, le comportement est attendu. –

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 
Questions connexes