如何获取PowerShell静态类方法中的当前类名/对象?

Ant*_*lov 5 reflection powershell

我需要$this在静态类中工作!怎么实现呢?任何解决方法?我已经分析Get-PSCallStack了类上下文的返回,发现没什么用处.

我需要这个用于(a)日志记录和(b)调用同一类的其他静态方法,而不是一次又一次地提及它的名字.

示例代码(PowerShell v5):

class foo {
    static [void]DoSomething() {
        [foo]::DoAnything()  #works

        #$this.DoAnything   #not working

        $static_this = [foo]
        $static_this::DoAnything() #works

    }
    static [void]DoAnything() {
        echo "Done"
    }
}

[foo]::DoSomething()
Run Code Online (Sandbox Code Playgroud)

Paw*_*Dyl 1

静态类没有this指针。参见MSDN

静态成员函数,因为它们存在于类级别而不是作为对象的一部分,所以没有 this 指针。在静态方法中引用 this 是错误的。

您必须通过类名调用方法。