Powershell Hashtable计数和键属性过载

Kiw*_*iwi 3 powershell hashtable key count

问题陈述:Count和Keys属性可能会因哈希值而过载,而不会返回其预期值.

我的Powershell代码是这样的:

$hash = @{}
$hash.one = "Number 1"
$hash.two = "Number 2"

"Count is [{0}]" -f $hash.Count
$hash.Count = "Count's Hash Value"
"Count is now [{0}]" -f $hash.Count
Run Code Online (Sandbox Code Playgroud)

我的输出是这样的:

Count is [2]
Count is now [Count's Hash Value]
Run Code Online (Sandbox Code Playgroud)

Count属性超载!这个问题可能会导致用户很难诊断出错误.让我感到很困惑.同样的问题适用于"钥匙"或实际上任何财产.

你对避免这种做法有什么想法吗?也许是一个不同的System.Collection?或者为所有键添加前缀,例如:

$key = ":" + $key 
Run Code Online (Sandbox Code Playgroud)

但是,它不是很优雅.即使现在我知道这个问题,我怀疑我会忘记并再次犯同样的错误.

我个人认为这是Powershell语言定义的一个问题.的.不应该允许表示法(如在$ hash.MyKey中)来检索哈希值,仅用于检索属性值.只是一个想法.:-)

谢谢你的帮助.

use*_*407 10

您可以直接调用属性get访问器而不是访问属性或使用Select-Object -ExpandProperty:

@{Count=123}.get_Count()
@{Count=123}|Select-Object -ExpandProperty Count # does not work on PowerShell Core
Run Code Online (Sandbox Code Playgroud)

在PowerShell v3 +中,您还可以使用PSBasePSObject自动属性:

@{Count=123;PSBase=$null}.PSBase.Count
@{Count=123;PSObject=$null}.PSObject.Properties['Count'].Value
Run Code Online (Sandbox Code Playgroud)

  • @Kiwi:有关背景信息,请参阅[GitHub 上的此讨论](https://github.com/PowerShell/PowerShell/issues/7758)。 (2认同)