问题描述
问题陈述:Count 和 Keys 属性可能会因散列值而过载,并且不会返回其预期值.
Problem Statement: The Count and Keys properties can get overloaded by a hash value and not return their expected values.
我的 Powershell 代码是这样的:
My Powershell Code is this:
$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 属性过载!这个问题可能会给用户带来一些很难诊断的错误.让我困惑了好一阵子.同样的问题适用于钥匙"或实际上任何财产.
The Count Property gets overloaded! This issues could cause users some very hard to diagnose bugs. Had me confused for a good while. Same issue applies to "Keys" or in fact any Property.
您对避免这种情况的最佳做法有什么想法吗?也许是不同的 System.Collection?或用一个字符作为所有键的前缀,例如:
Do you have any thoughts on best practice to avoid this one? Maybe a different System.Collection? or prefixing all Keys with a character such as:
$key = ":" + $key
然而,它不是很优雅.即使现在我知道这个问题,我怀疑我会忘记并再次犯同样的错误.
However, its not very elegant. Even now that I know the issue, I suspect I will forget and make the same mistake again.
我个人认为这是 Powershell 语言定义的问题.这 .符号(如在 $hash.MyKey 中)不应用于检索哈希值,只能用于检索属性值.只是一个想法.:-)
I personally think it is a problem with the Powershell Language Definition. The . notation (as in $hash.MyKey) should not be allowed for retrieving hash values, only for retrieving Property values. Just a thought. :-)
感谢您的帮助.
推荐答案
你可以直接调用属性get
访问器而不是访问属性或者使用Select-Object -ExpandProperty
:
You can directly call property get
accessor instead of accessing property or use Select-Object -ExpandProperty
:
@{Count=123}.get_Count()
@{Count=123}|Select-Object -ExpandProperty Count # does not work on PowerShell Core
在 PowerShell v3+ 中,您还可以使用 PSBase
或 PSObject
自动属性:
In PowerShell v3+ you could also use PSBase
or PSObject
automatic property:
@{Count=123;PSBase=$null}.PSBase.Count
@{Count=123;PSObject=$null}.PSObject.Properties['Count'].Value
这篇关于Powershell 哈希表计数和键属性超载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!