我尝试使用以下代码在我的 Powershell 代码中设置新词典。我希望字典使用元组作为键,使用 Arraylist 作为值(这样我就可以随着时间的推移向值添加项目)。
# Create dictionary
$mydict = [Collections.Generic.Dictionary[[Tuple[int,int]],Collections.ArrayList]]::new()
# Add an empty Arraylist to a key
$mydict.Add([Tuple]::Create(0,0),[Collections.ArrayList]::new())
# Try to add an item to this new arraylist
$mydict[(0,0)].Add(1)
MethodInvocationException: Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
# And sure enough:
$mydict[(0,0)].IsFixedSize
True
$mydict[(0,0)].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
有人知道为什么 Powershell 忽略我添加 ArrayList 作为成员的请求,并且出于某种原因默默地将对象转换为 System.Array 吗?
就像您使用
[Tuple]::Create(0,0)
一样,即在.Add()
调用中创建显式元组,您必须在尝试访问条目时使用相同的方法:
$null = $mydict[[Tuple]::Create(0,0)].Add(1)
原因是 PowerShell 的索引运算符 (
[…]
) 在设计上支持传递索引的数组,其元素被单独解释为要查找的索引。