如何在 PowerShell 中从数组创建 ArrayList? [英] How to create an ArrayList from an Array in PowerShell?

查看:111
本文介绍了如何在 PowerShell 中从数组创建 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组中的文件列表.我想枚举这些文件,并从中删除特定文件.显然我不能从数组中删除项目,所以我想使用 ArrayList.但以下对我不起作用:

I've got a list of files in an array. I want to enumerate those files, and remove specific files from it. Obviously I can't remove items from an array, so I want to use an ArrayList. But the following doesn't work for me:

$temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($temp)

其中 $temp 是一个数组.

我怎样才能做到这一点?

How can I achieve that?

推荐答案

我也无法让该构造函数工作.然而,这似乎有效:

I can't get that constructor to work either. This however seems to work:

# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)

您也可以在构造函数中传递一个整数来设置初始容量.

You can also pass an integer in the constructor to set an initial capacity.

你说要枚举文件是什么意思?为什么不能将想要的值过滤到一个新的数组中?

What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?

看来你可以像这样使用数组构造函数:

It seems that you can use the array constructor like this:

$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)

注意逗号.我相信正在发生的事情是,当您调用 .NET 方法时,您总是将参数作为数组传递.PowerShell 解压缩该数组并将其作为单独的参数传递给该方法.在这种情况下,我们不希望 PowerShell 解压数组;我们想将数组作为一个单元传递.现在,逗号运算符创建数组.因此 PowerShell 解压缩数组,然后我们使用逗号运算符再次创建数组.我认为这就是正在发生的事情.

Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.

这篇关于如何在 PowerShell 中从数组创建 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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