Powershell to C#



我正在使用一个powershell脚本,试图将其转换为C#程序,但我遇到了一个我正在努力解决的问题。该脚本使用$NameExample = @(),我认为它只是C#中的一个空数组——类似于decimal[] NameExample = new decimal[] {}

这里有更多的代码可以帮助,但我主要想弄清楚如何将$NameExample = @()声明为C#数组变量,任何事情都会有所帮助!感谢

$counter = 0
$UnitAvgerage = 20
$NameExample=@()
$NameExample2=@()
while ($counter -lt $NameExample.Count) 
{
$NameExample2 += $NameExample[$counter..($counter+$UnitAvg -1)] | measure-object -average
$counter += $NameExample2
}

数组是固定大小的数据结构,因此不能迭代构建

PowerShell使看起来像+=一样,但它在幕后所做的是每次创建一个新的数组,包括原始元素和新元素。

这是非常低效的,需要避免,即使在PowerShell代码中也是如此(尽管很方便(-请参阅此答案。

因此,在您的C#代码中,使用一个类似的数组(列表(类型,您可以有效地构建它,例如System.Collections.Generic.List<T>:

using System.Collections.Generic;
// ... 
// Create a list that can grow.
// If your list must hold objects of different types, use new List<object>()
var nameExample= new List<int>();
// ... use .Add() to append a new element to the list.
nameExample.Add(42);

最新更新