当我执行命令时:
$var = @{a=1;b=2}
在 Powershell(版本 3)中,$var
最终值为{System.Collections.DictionaryEntry, System.Collections.DictionaryEntry}
. 为什么会这样?如何存储我想要存储的值?
当我执行命令时:
$var = @{a=1;b=2}
在 Powershell(版本 3)中,$var
最终值为{System.Collections.DictionaryEntry, System.Collections.DictionaryEntry}
. 为什么会这样?如何存储我想要存储的值?
那是因为您的 ISE 正在枚举集合以创建变量树视图,并且从HashtableEnumerator
您获得的a 返回的对象$var.GetEnumerator()
是DictionaryEntry
-objects。
$var = @{a=1;b=2}
#Collection is a Hashtable
$var | Get-Member -MemberType Properties
TypeName: System.Collections.Hashtable
Name MemberType Definition
---- ---------- ----------
Count Property int Count {get;}
IsFixedSize Property bool IsFixedSize {get;}
IsReadOnly Property bool IsReadOnly {get;}
IsSynchronized Property bool IsSynchronized {get;}
Keys Property System.Collections.ICollection Keys {get;}
SyncRoot Property System.Object SyncRoot {get;}
Values Property System.Collections.ICollection Values {get;}
#Enumerated objects (is that a word?) are DictionaryEntry(-ies)
$var.GetEnumerator() | Get-Member -MemberType Properties
TypeName: System.Collections.DictionaryEntry
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = Key
Key Property System.Object Key {get;set;}
Value Property System.Object Value {get;set;}
您的值(1 和 2)存储在Value
对象的 -property 中,而它们Key
是您使用的 ID(a 和 b)。
当您需要枚举哈希表时,您只需要关心这一点,例如。当您遍历每个项目时。对于正常使用,这是幕后魔术,因此您可以使用$var["a"]
.