为什么我不能在类方法中使用预定义的变量? [英] Why can't I use predefined variables in class methods?

查看:82
本文介绍了为什么我不能在类方法中使用预定义的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在类方法中使用预定义的变量,如 $PSVersionTable 或 $PSScriptRoot.他们因错误消息而失败

I tried to use predefined variables like $PSVersionTable or $PSScriptRoot in a class method. They failed with the error message

方法中未分配变量.

示例:

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

对于为什么"部分,我想这与范围有关.在您的类中,您必须以某种方式指定您引用全局 $PSVersionTable 变量,而不是类或脚本范围内的某些内容.

For the "why" part, I guess this is related to scope. In your class you have to specify in some way that you refer to the global $PSVersionTable variable, and not to something in the class or script scope.

这篇关于为什么我不能在类方法中使用预定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆