【问题标题】:How can I recognize a generic class?如何识别泛型类?
【发布时间】:2010-03-19 13:24:06
【问题描述】:

如何识别 (.NET 2) 泛型类?

Class A(Of T)
End Class

' not work '
If TypeOf myObject Is A Then

?

【问题讨论】:

    标签: .net vb.net generics


    【解决方案1】:

    如果是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;
    

    【讨论】:

    • ?(new List(of object)).GetType().GetGenericTypeDefinition is gettype(List(of ))
    • 对非泛型类型抛出异常:?(new ArrayList).GetType().GetGenericTypeDefinition is gettype(List(of )) 由于对象的当前状态,操作无效。
    • 是的,这是预期的行为。
    • 不好。 class B : A(Integer) 此代码不适用于 B。
    • 是的,因为 B 不是泛型类型。如果需要,可以使用 type.BaseType() 方法向上遍历类型层次结构。
    【解决方案2】:
      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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多