且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PowerShell 中从数组创建 ArrayList?

更新时间:2023-11-17 13:06:58

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

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.