PowerShell 和 StringBuilder [英] PowerShell And StringBuilder
问题描述
我是 PowerShell 的新手,但熟悉 .NET 类.
I am new in PowerShell but am familiar with .NET classes.
我在 PowerShell 脚本中使用 System.Text.StringBuilder
.脚本是这样的
I am using System.Text.StringBuilder
in PowerShell script. The script is that
Function MyStringFunc([String]$line) {
$r = New-Object -TypeName "System.Collections.Generic.List``1[[System.String]]";
$sb = New-Object -TypeName "System.Text.StringBuilder";
foreach ($c in $line) {
$sb.Append($c);
$r.Add($sb.ToString());
}
return $r;
}
$line1 = "123";
$a = MyStringFunc $line1;
$a
我期望的结果是
1
12
123
结果是
Capacity MaxCapacity Length
-------- ----------- ------
16 2147483647 3
123
我做错了吗?
推荐答案
StringBuilder 上的几个方法,如 Append IIRC,返回 StringBuilder 以便您可以调用更多 StringBuilder 方法.然而 PowerShell 的工作方式是它输出所有结果(在 .NET 方法调用的情况下返回值).在这种情况下,将结果强制转换为 [void]
以忽略返回值,例如:
Several of the methods on StringBuilder like Append IIRC, return the StringBuilder so you can call more StringBuilder methods. However the way PowerShell works is that it outputs all results (return values in the case of .NET method calls). In this case, cast the result to [void]
to ignore the return value e.g.:
[void]$sb.Append($c)
请注意,在 PowerShell 中,您不需要在 ;
中结束行.但是,如果您将多个命令放在同一行上,则使用 ;
' 来分隔这些命令.
Note that you don't need to end lines in ;
in PowerShell. However if you put multiple commands on the same line then use ;
' to separate those commands.
这篇关于PowerShell 和 StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!