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)
| 归档时间: |
|
| 查看次数: |
3209 次 |
| 最近记录: |