2016-09-22 23 views
0

我有System.Type對象(retType)。我通過我的政策對象獲得了反思。我如何測試以查看它的枚舉?任何幫助將是最令人欣賞的代碼如下。VB.Net檢查Type是否爲IEnumerable

Public Shared Function SerializeChanges(p As Model.Policy_2.Policy) As XmlDocument 

    Dim polProps As PropertyInfo() = p.GetType().GetProperties() 
     For Each pi As PropertyInfo In polProps 
     Dim retType As Type = pi.PropertyType 
     ' This line belowthrows an error that IEnumerable is an Interface and cannot be used as an expression 
     If retType Is IEnumerable Then 
      'Do Stuff 

     End If 
End Function 

回答

0

下面的方法是檢查給定類型是否繼承或實現另一類型的通用方法:

Function InheritsOrImplements(child As Type, parent As Type) As Boolean 
    If child Is Nothing OrElse parent Is Nothing Then 
     Return False 
    End If 

    parent = resolveGenericTypeDefinition(parent) 

    If parent.IsAssignableFrom(child) Then 
     Return True 
    End If 

    Dim currentChild = If(child.IsGenericType, child.GetGenericTypeDefinition(), child) 

    While currentChild <> GetType(Object) 
     If parent = currentChild OrElse hasAnyInterfaces(parent, currentChild) Then 
      Return True 
     End If 

     currentChild = If(currentChild.BaseType IsNot Nothing AndAlso currentChild.BaseType.IsGenericType, currentChild.BaseType.GetGenericTypeDefinition(), currentChild.BaseType) 

     If currentChild Is Nothing Then 
      Return False 
     End If 
    End While 

    Return False 
End Function 

Function hasAnyInterfaces(parent As Type, child As Type) As Boolean 
    Return child.GetInterfaces().Any(Function(childInterface) 
     Dim currentInterface = If(childInterface.IsGenericType, childInterface.GetGenericTypeDefinition(), childInterface) 

     Return currentInterface = parent 

    End Function) 
End Function 

Function resolveGenericTypeDefinition(type As Type) As Type 
    Dim shouldUseGenericType = Not (type.IsGenericType AndAlso type.GetGenericTypeDefinition() <> type) 
    If type.IsGenericType AndAlso shouldUseGenericType Then 
     type = type.GetGenericTypeDefinition() 
    End If 
    Return type 
End Function 

https://github.com/shaynevanasperen/Quarks/blob/master/Quarks/TypeExtensions/InheritsOrImplements.cs

用法摘自:

InheritsOrImplements(retType, GetType(IEnumerable))