Can I add a key named 'keys' to a hashtable without overriding the 'keys' member

血红的双手。 提交于 2020-04-13 07:11:10

问题


It seems that I cannot add an arbitrary key name to a hashtable without overriding a member with that name if it already exists.

I create a hash table ($x) and add two keys, one and two:

$x = @{}

$x['one'] = 1
$x['two'] = 2

The added keys are then shown by evaluating $x.Keys:

$x.Keys

This prints:

one
two

If I add another key, named keys, it overrides the already existing member:

$x['Keys'] = 42

$x.Keys

This now prints:

42

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.

Is it somehow possible to add a key named Keys without overriding the Keys member?


回答1:


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

For cases where collisions are unpredictable, you can use the hidden member method get_Keys() as in this question.

$hash.get_Keys()


来源:https://stackoverflow.com/questions/60803441/can-i-add-a-key-named-keys-to-a-hashtable-without-overriding-the-keys-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!