我可以在不覆盖'keys'成员的情况下将名为'keys'的键添加到哈希表中吗 [英] Can I add a key named 'keys' to a hashtable without overriding the 'keys' member
问题描述
似乎我不能在hashtable
上添加任意键名称,而不能覆盖具有该名称的成员(如果该名称已经存在的话).
It seems that I cannot add an arbitrary key name to a hashtable
without overriding a member with that name if it already exists.
我创建一个哈希表($x
)并添加两个键one
和two
:
I create a hash table ($x
) and add two keys, one
and two
:
$x = @{}
$x['one'] = 1
$x['two'] = 2
然后通过评估$x.Keys
来显示添加的键:
The added keys are then shown by evaluating $x.Keys
:
$x.Keys
此打印:
one
two
如果我添加另一个名为keys
的密钥,它将覆盖现有成员:
If I add another key, named keys
, it overrides the already existing member:
$x['Keys'] = 42
$x.Keys
现在打印:
42
我不确定是否发现此行为是理想的.我曾期望$x.keys
打印键名,而$x['keys']
打印键名.
I am not sure if I find this behavior desirable. I had expected $x.keys
to print the key names and $x['keys']
to print 42
.
是否可以在不覆盖Keys
成员的情况下添加名为Keys
的密钥?
Is it somehow possible to add a key named Keys
without overriding the Keys
member?
推荐答案
在您的示例中,成员属性Keys
仍然存在.使用成员访问运算符语法object.property
不再可以访问它.您可以通过深入到PSObject
子属性来查看该属性.
In your example, the member property Keys
still exists. It is just no longer accessible using the member access operator syntax object.property
. You can see the property by drilling down into the PSObject
sub-properties.
$x.PSObject.Members['Keys'].Value
The documentation for Hash Tables considers the scenario for property collisions. The recommendation for those cases is to use hashtable.psbase.Property
.
$x.PSBase.Keys
对于无法预测的冲突,您可以使用get_Keys()
的隐藏成员方法,如
For cases where collisions are unpredictable, you can use the hidden member method get_Keys()
as in this question.
$hash.get_Keys()
这篇关于我可以在不覆盖'keys'成员的情况下将名为'keys'的键添加到哈希表中吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!