Powershell为Func <T>而不是Action <T>创建脚本块

Mar*_*ark 3 c# powershell overloading scriptblock

我正在尝试从Powershell使用一个类。此类具有一种称为的方法,该方法Execute()具有两个重载:一个重载了Func<T>,一个重载了Action<T>。我可以调用Action<T>以scriptblock为委托的重载,但是我不知道如何调用以a为代表的重载Func<T>

add-type -TypeDefinition @'
using System;

public class DelegTest
{
    public R Execute<R>(Func<R> method)
    {
        return method();
    }

    public void Execute(Action method)
    {
        Execute(() => { method(); return true; });
    }
}
'@

$t = new-object DelegTest
$t.Execute({ 1 + 1 }) # returns nothing
Run Code Online (Sandbox Code Playgroud)

我怎么称呼需要一个的过载Func<T>?我认为这将需要创建一个具有返回类型的ScriptBlock,但是我不知道该怎么做。Powershell解析器显然不够智能,无法自动执行此操作。

use*_*407 7

您需要自己强制转换ScriptBlock为正确的委托人类型:

$t.Execute([Func[int]]{ 1 + 1 })
Run Code Online (Sandbox Code Playgroud)