保留PowerShell函数返回类型

Dar*_*kin 9 powershell casting

在我的PowerShell脚本中,我需要使用以下签名调用.NET方法:

class CustomList : System.Collections.Generic.List<string> { }

interface IProcessor { void Process(CustomList list); }
Run Code Online (Sandbox Code Playgroud)

我做了一个帮助函数来生成列表:

function ConvertTo-CustomList($obj)
{
    $list = New-Object CustomList
    if ($obj.foo) {$list.Add($obj.foo)}
    if ($obj.bar) {$list.Add($obj.bar)}
    return $list
}
Run Code Online (Sandbox Code Playgroud)

然后我调用方法:

$list = ConvertTo-CustomList(@{'foo'='1';'bar'='2'})
$processor.Process($list)
Run Code Online (Sandbox Code Playgroud)

但是,调用失败并出现以下错误:

Cannot convert argument "list", with value: "System.Object[]", for "Process" to type "CustomList"
+ CategoryInfo          : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Run Code Online (Sandbox Code Playgroud)

所以PowerShell由于某种原因将CustomList带有两个项目的a转换为带有两个项目的object[]项目,并且无法在方法调用时将其转换回来.如果我打电话ConvertTo-CustomList(@{'foo'='1'}),只string返回一个.

我试图在这里和那里放一个演员,但这没有帮助,在函数返回后执行失败.

那么如何强制ConvertTo-CustomList函数返回原文CustomList呢?我不想初始化CustomList就地,因为在实际代码中初始化比在这个例子中更复杂.

一种可能的解决方法是使用Add-Type命令行开关在C#中实现辅助函数,但我更希望将代码保持为单一语言.

Mat*_*sen 11

return $list
Run Code Online (Sandbox Code Playgroud)

导致集合解体并逐个"管道化".这就是PowerShell的本质.

您可以通过使用一元数组运算符将输出变量本身包装在一个单项数组中来防止这种情况,:

return ,$list
Run Code Online (Sandbox Code Playgroud)

  • "一个包含`$ list`对象的数组"然后在赋值时自动解压缩 (2认同)
  • @TessellatingHeckler:你的ArrayList示例返回object []的唯一原因是ArrayList的Add()方法返回一个值(旧元素计数),它污染了函数的输出流,从而返回一个常规PS数组(object []),其中_last_ element是ArrayList.如果你使用泛型类型(例如,`System.Collections.Generic.List [string]`),你会看到Mathias的声明是正确的(或者,使用`$ null = $ list.Add(...)` ). (2认同)