【发布时间】:2018-02-16 17:43:54
【问题描述】:
谁能解释这种奇怪的 powershell 行为。
如果我声明以下内容:
$MyCollection = New-Object System.Collections.ArrayList
$MyCollection.Add(@{'Val1'=1; 'Val2'=2; 'Val3'=3})
$MyCollection.Add(@{'Val1'=1; 'Val2'=2; 'Val3'=3})
$MyCollection.Add(@{'Val1'=1; 'Val2'=2; 'Val3'=3})
所以...我应该有一个看起来像这样的对象:
System.Collections.Array.List
Index Item
0 {System.Collections.HashTable}
1 {System.Collections.HashTable}
2 {System.Collections.HashTable}
但是,如果我获得会员,您会看到我的整个收藏都变成了一个大哈希表
$MyCollection | Get-Member
TypeName: System.Collections.Hashtable
Name MemberType Definition
---- ---------- ----------
Add Method void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
Clear Method void Clear(), void IDictionary.Clear()
Clone Method System.Object Clone(), System.Object ICloneable.Clone()
Contains Method bool Contains(System.Object key), bool IDictionary.Contains(System.Object key)
ContainsKey Method bool ContainsKey(System.Object key)
ContainsValue Method bool ContainsValue(System.Object value)
CopyTo Method void CopyTo(array array, int arrayIndex), void ICollection.CopyTo(array array, int index)
Equals Method bool Equals(System.Object obj)
GetEnumerator Method System.Collections.IDictionaryEnumerator GetEnumerator(), System.Collections.IDictionaryEnumerator IDictionary.GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEn...
GetHashCode Method int GetHashCode()
GetObjectData Method void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context), void ISerializable.GetObjectData(System.Runtime....
GetType Method type GetType()
OnDeserialization Method void OnDeserialization(System.Object sender), void IDeserializationCallback.OnDeserialization(System.Object sender)
Remove Method void Remove(System.Object key), void IDictionary.Remove(System.Object key)
ToString Method string ToString()
Item ParameterizedProperty System.Object Item(System.Object key) {get;set;}
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;}
而且行为是这样的。例如,我无法以我想要的方式访问我的对象:
$MyCollection | %{$_.Val1}
输出
1
1
1
预期输出
1
如您所见,我们现在有一个具有非常奇怪行为的大型哈希表。谁能解释一下Powershell实际上在做什么?因为它绝对不会访问 ArrayList 集合中的 HashTable。
它就像调用任何 cmdlet 一样将我的数据结构扁平化为单个哈希表
【问题讨论】:
-
您希望
$MyCollection | %{$_.Val1}示例的输出是什么?当前输出将与我对语法的期望一样。
标签: powershell arraylist collections hashtable