强类型字典内容

问题描述

作为从 PS2.0、函数和脚本快速实践到 PS5.0、类和编程最佳实践的大型 PowerShell 程序重构的一部分,我一直在转向无处不在的强类型,并找到了一些地方问题。最新的一个是哈希表。 使用 [Array][Hashtable],您可以混合使用内容,这使得枚举该集合无法进行强类型化。对于数组,您可以选择 [String[]] 或使用 [System.Collections.Generic.List[String]] 移动到通用列表。但是字典似乎提出了一个问题。我找不到创建字典并将其值限制为特定类型的方法。像 [System.Collections.Specialized.OrderedDictionary[Int32,Int32]] 这样的东西失败了。 那么,有没有一种方法可以使 Dictionaries 和 OrderedDictionaries 具有索引、值或两者的强类型化?如果没有办法,这算是一个必须克服的问题,还是不是问题,如果是,为什么不是问题?

解决方法

您可以创建泛型字典,但根据 Create new System.Collections.Generic.Dictionary object fails in PowerShell,您必须使用反引号来对泛型类型参数列表中的逗号进行转义:

例如

PS> $dict = new-object System.Collections.Generic.Dictionary[int`,string]

请注意,PowerShell 仍会尽力强制类型,因此只有在无法转换类型时才会抛出异常:

PS> $dict.Add("1","aaa") # equivalent to $dict.Add(1,"aaa")

而且我不相信 有一个通用的开箱即用的 OrderedDictionary,这可能就是失败的原因:-)

PS> new-object System.Collections.Specialized.OrderedDictionary[Int32`,Int32]
New-Object: Cannot find type [System.Collections.Specialized.OrderedDictionary[Int32,Int32]]: verify that the assembly containing this type is loaded.