在我的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#中实现辅助函数,但我更希望将代码保持为单一语言.
如何在每次保存文档之前使Microsoft Word运行VBA宏?可以在不将宏添加到文档本身的情况下完成吗?