Возможно, есть лучший способ, но вот что будет работать:
Dim t = obj.GetType()
If t.IsGenericType AndAlso
t.GetGenericTypeDefinition().FullName = "System.Collections.Generic.Dictionary`2" Then
EDIT:
На самом деле, есть лучший способ:
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