在我的 PowerShell 脚本中,我需要使用以下签名调用 .NET 方法:
class CustomList : System.Collections.Generic.List<string> { }
interface IProcessor { void Process(CustomList list); }
我创建了一个辅助函数来生成列表:
function ConvertTo-CustomList($obj)
{
$list = New-Object CustomList
if ($obj.foo) {$list.Add($obj.foo)}
if ($obj.bar) {$list.Add($obj.bar)}
return $list
}
然后我调用该方法:
$list = ConvertTo-CustomList(@{'foo'='1';'bar'='2'})
$processor.Process($list)
但是,调用失败并出现以下错误:
Cannot convert argument "list", with value: "System.Object[]", for "Process" to type "CustomList"
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
因此 PowerShell 出于某种原因将CustomList
有两个项目object[]
有两个项目,无法在方法调用时将其转换回来。如果我打电话ConvertTo-CustomList(@{'foo'='1'})
,只是一个string
被返回。
我尝试到处进行强制转换,但这没有帮助,在函数返回后的强制转换点执行失败。
那么怎样才能强制ConvertTo-CustomList
返回原始函数CustomList
?我不想初始化CustomList
就地,因为在实际代码中,初始化比本示例中的更复杂。
一种可能的解决方法是使用 C# 实现辅助函数Add-Type
commandlet,但我更愿意将我的代码保留为单一语言。