gpt4 book ai didi

powershell - 奇怪的字符串生成器

转载 作者:行者123 更新时间:2023-12-03 08:29:34 26 4
gpt4 key购买 nike

我在函数内部有 StringBuilder 对象。有字符串型返回前还有一些系统对象 后。

function test
{
$strArr = @("aaa", "bbb", "ccc")
$stringBuilder = New-Object System.Text.StringBuilder
foreach ($item in $strArr)
{
$stringBuilder.AppendLine($item)
}
$out = $stringBuilder.ToString()
write-host "FIRST OUT: ", $out, "OUTTYPE:", $out.GetType()
return $out
}

$out2 = test
Write-Host "-------------------"
write-host "SECOND OUT2: ", $out2, "OUT2TYPE:", $out2.GetType()

输出:
FIRST OUT:  aaa
bbb
ccc
OUTTYPE: System.String -> THAT'S OK
-------------------
SECOND OUT2 (ALL ARE four times - WHY???): aaa
bbb
ccc
aaa
bbb
ccc
aaa
bbb
ccc
aaa
bbb
ccc
OUT2TYPE: System.Object[] -> Object?????

为什么都是四次?为什么对象不是字符串?

最佳答案

试试这个:

function test

{
$strArr = @("aaa", "bbb", "ccc")
$stringBuilder = New-Object System.Text.StringBuilder
foreach ($item in $strArr)
{
$stringBuilder.AppendLine($item) | Out-Null
}
$out = $stringBuilder.ToString()
write-host "FIRST OUT: ", $out, "OUTTYPE:", $out.GetType()
return $out
}

$out2 = test
Write-Host "-------------------"
write-host "SECOND OUT2: ", $out2, "OUT2TYPE:", $out2.GetType()

解释是 $stringBuilder.AppendLine()输出一些东西,它被添加到函数的输出中。

编辑:
函数输出的一切都被认为是函数的返回。换句话说,在PowerShell中,函数的返回值不仅仅是 return之后的值。 keywork ($out) 而是函数内部输出的所有数据(以数组形式)。看着 about_Return我们看到

In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword.

关于powershell - 奇怪的字符串生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com