可能有更好的方法,但这里有一些可行的方法:
Dim t = obj.GetType()
If t.IsGenericType AndAlso
t.GetGenericTypeDefinition().FullName = "System.Collections.Generic.Dictionary`2" Then
编辑:
其实还有更好的办法:
If t.IsGenericType AndAlso
t.GetGenericTypeDefinition() Is GetType(Dictionary(Of ,)) Then
您可以在使用GetType 时省略泛型类型参数,但这将创建一个与任何特定Dictionary(Of TKey, TValue) 类型不匹配的泛型类型定义,因此您不能只将其添加到您的Select Case:
Case GetType(Dictionary(Of ,))
编辑 2:
我只是把这个可能有用的扩展方法放在一起:
Imports System.Runtime.CompilerServices
Public Module TypeExtensions
<Extension>
Public Function MatchesGenericType(source As Type, genericType As Type) As Boolean
If genericType Is Nothing Then
Throw New ArgumentNullException(NameOf(genericType))
End If
If Not genericType.IsGenericType Then
Throw New ArgumentException("Value must be a generic type or generic type definition.", NameOf(genericType))
End If
Return source.IsGenericType AndAlso
(source Is genericType OrElse
source.GetGenericTypeDefinition() Is genericType)
End Function
End Module
示例用法:
Module Module1
Sub Main()
Dim testTypes = {GetType(String),
GetType(List(Of )),
GetType(List(Of String)),
GetType(Dictionary(Of ,)),
GetType(Dictionary(Of String, String))}
Dim comparisonTypes = {Nothing,
GetType(String),
GetType(List(Of )),
GetType(List(Of String)),
GetType(Dictionary(Of ,)),
GetType(Dictionary(Of String, String))}
For Each testType In testTypes
For Each comparisonType In comparisonTypes
Console.Write($"Comparing type '{testType.Name}' to {If(comparisonType?.IsGenericTypeDefinition, "type definition", "type")} '{comparisonType?.Name}': ")
Try
Console.WriteLine(testType.MatchesGenericType(comparisonType))
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
Next
Console.ReadLine()
End Sub
End Module
例子:
GetType(Dictionary(Of String, String)).MatchesGenericType(Nothing) 'Throws exception
GetType(Dictionary(Of String, String)).MatchesGenericType(GetType(String)) 'Throws exception
GetType(Dictionary(Of String, String)).MatchesGenericType(GetType(List(Of String))) 'Returns False
GetType(Dictionary(Of String, String)).MatchesGenericType(GetType(Dictionary(Of String, String))) 'Returns True
GetType(Dictionary(Of String, String)).MatchesGenericType(GetType(Dictionary(Of ,))) 'Returns True
GetType(Dictionary(Of ,)).MatchesGenericType(GetType(Dictionary(Of String, String))) 'Returns False
GetType(Dictionary(Of ,)).MatchesGenericType(GetType(Dictionary(Of ,))) 'Returns True