为什么我不能在 class 方法中使用预定义变量?

Why can't I use predefined variables in class methods?

我尝试在 class 方法中使用 $PSVersionTable 或 $PSScriptRoot 等预定义变量。他们失败并显示错误消息

Variable is not assigned in the method.

示例:

Class Foo {
    [String]$Version

    GetVersion() {
        If ($PSVersionTable) {
            $this.Version = $PSVersionTable.PSVersion
        }
    }
}

但是为什么呢?

Class Foo {
    [String] $Version

    GetVersion() {
        if ($global:PSVersionTable) {
            $this.Version = $global:PSVersionTable.PSVersion
        }
    }
}

$foo = [Foo]::new()

$foo.GetVersion()

Write-Host $foo.Version

对于"why"部分,我猜这与范围有关。在您的 class 中,您必须以某种方式指定您引用的是全局 $PSVersionTable 变量,而不是 class 或脚本范围内的内容。