gpt4 book ai didi

Powershell 哈希表计数和键属性重载

转载 作者:行者123 更新时间:2023-12-03 13:19:36 30 4
gpt4 key购买 nike

问题陈述 :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

我的输出是这样的:
Count is [2]
Count is now [Count's Hash Value]

Count 属性重载!这个问题可能会给用户带来一些很难诊断的错误。让我困惑了好一阵子。同样的问题适用于“ key ”或实际上任何属性(property)。

您对避免这种情况的最佳实践有什么想法吗?也许是不同的 System.Collection?或用一个字符作为所有键的前缀,例如:
$key = ":" + $key 

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

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

谢谢你的帮助。

最佳答案

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

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

在 PowerShell v3+ 中,您还可以使用 PSBasePSObject 自动属性:
@{Count=123;PSBase=$null}.PSBase.Count
@{Count=123;PSObject=$null}.PSObject.Properties['Count'].Value

关于Powershell 哈希表计数和键属性重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716939/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com