0

I want to use a func delegate in my static PowerShell 5.0 class:

I had issues to find a way to assign other static class methods for my delegate.

This code is working but not very convinient.

Is there a better way to use a delegate here ?

And I need to instanciate my static! class, only to get the type.

I tried the outcommented line, how you would do it with .NET types, but it's not working for my own class.

How can I get the type of my static class here more elegant ?

And, BTW, GetMethod() did not accecpt the BindingFlags parameter, why ?

class Demo
{
    hidden static [object] Method_1([string] $myString)
    {
        Write-Host "Method_1: $myString"
        return "something"    
    }

    hidden static [object] Method_2([string] $myString)
    {
        Write-Host "Method_2: $myString"    
        return $null    
    }

    hidden static [object] TheWrapper([string]$wrappedMethod, [string] $parameter)
    {
        # do a lot of other stuff here... 

        #return [System.Type]::GetType("Demo").GetMethod($wrappedMethod).CreateDelegate([Func``2[string, object]]).Invoke($parameter)
        return [Demo]::new().GetType().GetMethod($wrappedMethod).CreateDelegate([Func``2[string, object]]).Invoke($parameter)    
    }

    static DoWork()
    {
        Write-Host ([Demo]::TheWrapper('Method_1', 'MyMessage'))
        [Demo]::TheWrapper('Method_2', 'c:\my_file.txt')
    }
}

[Demo]::DoWork()
2
  • 1
    [Demo]::new().GetType() -> [Demo] Commented May 16, 2018 at 23:12
  • first question answered, Thanks :-) Commented May 16, 2018 at 23:24

1 Answer 1

1

You don't need to create an instance of [demo] since [demo] is the actual type of the class. Also, you can write the delegate type more simply as [Func[string,object]]. This simplifies the body of TheWrapper method to

return [Demo].GetMethod($wrappedMethod).CreateDelegate([Func[string, object]]).Invoke($parameter)

but a much simpler way to do this in PowerShell is to get the method by passing its name to the '.' operator then invoking the result:

return [demo]::$wrappedMethod.Invoke($parameter)

In PowerShell, the right-hand side of the '.' operator doesn't need to be a constant. You can use an expression that results in the name of the method (or property) to retrieve.

Sign up to request clarification or add additional context in comments.

2 Comments

Is any particular reason to use [demo]::$wrappedMethod.Invoke($parameter) over [demo]::$wrappedMethod($parameter)?
Thank you so much :-) I always forget how simple you can achive such things in script languages, but isn't it a safer way to explicitly use a C# delegate ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.