在Powershell中调用另一个方法返回的方法

问题描述 投票:0回答:1

我正在尝试调用从另一个函数返回的函数。基本上我有一堆函数根据某些条件被调用:

function func1 {write-host "hello func1"}
function func2 {write-host "hello func2"}
# ...

function getfunc([char]$condition) {
    switch ($condition) {
        '1' {return func1}
        '2' {return func2}
        # ...
    }
}

function main {
    &getfunc('1')
}

调用

main
会产生正确的结果
hello func1
。但是,我似乎无法使这些方法适用于类方法,因为它们要求我指定方法的返回值的类型:

class MyClass {

    [char]$condition

    [void] func1() {write-host "hello func1"}
    [void] func2() {write-host "hello func2"}
    # ...

    [string[]] getfunc() {        # what type to put in here ?
        switch ($this.condition) {
            '1' {return $this.func1}
            '2' {return $this.func2}
            # ...
        }
        return ""
    }

    [void] main() {
        $this.condition = '1'
        & $this.getfunc()
    }
}

[MyClass]::new().main()

我尝试使用

[string[]]
但没有运气:

& : The term 'void func1()' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

我该怎么做?

powershell
1个回答
0
投票

像示例中那样取消引用类方法会生成

System.Management.Automation.PSMethod
类型的对象 - 您可以通过
Invoke()
方法调用它,但不能通过
&
调用它,所以这样做:

class MyClass {
    [void] func1() { Write-host "hello func1" }
    [void] func2() { Write-host "hello func2" }

    static [void] Main([int]$condition) {
        $inst = [MyClass]::new()
        # select function
        $func = switch ($condition) {
            1 { $inst.func1 }
            2 { $inst.func2 }
        }
        # invoke selected function
        $func.Invoke()
    }
}

[MyClass]::main(1)
© www.soinside.com 2019 - 2024. All rights reserved.