Powershell哈希表计数和键属性变得超载 [英] Powershell Hashtable Count and Keys Properties getting overloaded

查看:61
本文介绍了Powershell哈希表计数和键属性变得超载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题声明: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?或在所有Key前面加上诸如以下字符:

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 +中,您还可以使用PSBasePSObject自动属性:

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哈希表计数和键属性变得超载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆