如何判断一个对象是否为任意键值类型的Dictionary?
如何判断一个对象是否为任意键值类型的Dictionary?
我最近需要实现一个功能:判断某个对象是不是任意泛型参数的Dictionary。一开始自己写了一段代码,还参考了ChatGPT的建议,不过测试后发现有问题,这里把整个过程和修正后的解决方案分享给大家。
最开始尝试的代码是这样的:
Function IsDictionary(value As Object) As Boolean ' Get the type of the value Dim valueType = value.GetType() ' Check if the type is a generic type and if it's a Dictionary If valueType.IsGenericType Then ' Get the generic type definition Dim genericTypeDef = valueType.GetGenericTypeDefinition() ' Check if it's a Dictionary(Of TKey, TValue) If genericTypeDef Is GetType(Dictionary(Of Object, Object)) Then ' It's a Dictionary, but we don't know the types of the keys and values Return True End If End If Return False End Function
这段代码存在一个关键问题:它只认Dictionary(Of Object, Object)这种具体的泛型实例,像Dictionary(Of String, Integer)、Dictionary(Of Integer, String)这类不同键值类型的Dictionary都会被误判为不是Dictionary。本质原因是:所有泛型Dictionary的泛型类型定义都是同一个——Dictionary(Of TKey, TValue),而非某个具体的泛型参数组合。
所以我修正了判断逻辑,改为对比泛型类型定义是否等于GetType(Dictionary(Of ,))(逗号表示这是需要两个泛型参数的类型定义),修正后的代码如下:
Function IsDictionary(value As Object) As Boolean If value Is Nothing Then Return False End If Dim valueType = value.GetType() ' 先判断是否为泛型类型,再对比泛型定义 If valueType.IsGenericType Then Dim genericTypeDef = valueType.GetGenericTypeDefinition() Return genericTypeDef Is GetType(Dictionary(Of ,)) End If Return False End Function
为了验证正确性,我做了几个测试案例:
' 测试用例 Dim dict1 As New Dictionary(Of String, Integer) From {{"key1", 1}, {"key2", 2}} Dim dict2 As New Dictionary(Of Integer, String) From {{1, "one"}, {2, "two"}} Dim notADictionary As New List(Of String) From {"item1", "item2"} ' 调用函数测试 Console.WriteLine(IsDictionary(dict1)) ' 输出 True Console.WriteLine(IsDictionary(dict2)) ' 输出 True Console.WriteLine(IsDictionary(notADictionary)) ' 输出 False
测试结果完全符合预期:不管Dictionary的键值是什么类型,都能被正确识别;非Dictionary类型的对象则会被正确排除。
备注:内容来源于stack exchange,提问作者Andri Timur
相关产品推荐
相关产品推荐

