Powershell create scriptblock for Func<T> instead of Action<T>
Asked Answered
H

1

5

I have a class I'm attempting to use from Powershell. This class has a method, called Execute(), with two overloads: one which takes a Func<T> and one which takes an Action<T>. I can call the overload that takes an Action<T> using a scriptblock as the delegate, but I cannot figure out how to call the overload that takes 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

How do I call the overload that takes a Func<T>? I assume this would require creating a ScriptBlock that has a return type, but I don't know how to do this; the Powershell parser apparently isn't smart enough to do this automatically.

Hypopituitarism answered 10/5, 2016 at 18:49 Comment(2)
Execute([Func[int]]{ 1 + 1 })Somali
That works... make it and answer and I'll select itHypopituitarism
S
9

You need to cast ScriptBlock to right delegate type by yourself:

$t.Execute([Func[int]]{ 1 + 1 })
Somali answered 10/5, 2016 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.