在 PowerShell 中使用 .NET 集合(ArrayList、List 等)的一个问题 [英] A gotcha of using .NET collections (ArrayList, List,..) in PowerShell

查看:57
本文介绍了在 PowerShell 中使用 .NET 集合(ArrayList、List 等)的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到这一点,并且通过艰难的方式学到了它,所以我想分享一下.假设您有以下字符串列表:

I just realized this and I've learned it the hard way, so I want to share. Consider you have the following list of strings:

>$list = New-Object -TypeName System.Collections.Generic.List[string]
>$list.Add("x")
>$list.Add("yy")
>$list.Add("zzz")
>$list
x
yy
zzz

现在,如果您想获取列表中的项目数,您可以访问 .Count 属性,它会按预期为您提供3".

Now if you want to get the number of items in the list, you would access the .Count property, and it gives you "3" as expected.

>$list.Count
3

但是,有时访问 .Length 而不是 .Count 会出错.在其他语言(如 Python 或 C#)中,您会收到一条错误消息,指出此属性不可用.但在 PowerShell 中,结果证明,如果在该对象上找不到它,它会遍历包含的对象并访问它们的属性.所以你最终得到了一个长度列表!惊喜!!

However, sometimes you would make mistake by accessing .Length instead of .Count. In other languages, like Python or C#, you would get an error saying this property is not available. But in PowerShell, it turns out that, if it's not found on that object, it iterates through the contained objects and access the property on them. So you end up having a list of Lengthes! Surprise!!

>$list.Length
1
2
3

您甚至可以调用方法!

>$list.ToUpper()
X
YY
ZZZ

请注意,正如我所尝试的,此功能"也适用于 System.Collections.ArrayList.但它不适用于 PowerShell 的内置数组类型.

Note that, as I've tried, this "feature" also works for System.Collections.ArrayList. But it does not work for PowerShell's builtin array type.

这个功能"叫什么?为什么它是这样设计的?这非常令人惊讶且容易出错.

What is this "feature" called? And why is it designed such way? It's very surprising and error-prone.

推荐答案

Keith Hill 在评论中提到这是 V3 中一个叫做 Member Enumeration 的新功能.

Keith Hill mentioned in the comment that this is a new feature called Member Enumeration in V3.

请参阅新的 V3 语言功能"在 devblogs.microsoft.com 上.

Refer to "New V3 Language Features" on devblogs.microsoft.com.

这篇关于在 PowerShell 中使用 .NET 集合(ArrayList、List 等)的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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