在 Powershell 中的静态方法中引用静态成员 Class

Reference Static member in Static Method In a Powershell Class

为什么静态直接访问失败,但间接访问有效?请注意,加载的文件在两个示例中均有效。

使用 Direct To Static 失败

class OpPrj {

[string] $ProjectPath

static [string] $configFile = 'settings.json';

[OpPrj] static GetSettings(){
   return [OpPrj](Get-Content [OpPrj]::configFile | Out-String|ConvertFrom-Json);
}

通过分配给本地工作

class OpPrj {

  [string] $ProjectPath

  static [string] $configFile = 'settings.json';

  [OpPrj] static GetSettings(){
      $file = [OpPrj]::configFile
      Write-Host $file  # outputs settings.json
      return [OpPrj](Get-Content $file | Out-String | ConvertFrom-Json);
  }

您在调用 Get-Content 时存在语法错误:

Get-Content [OpPrj]::configFile

PowerShell 解析器无法确定其结束位置(我不确定原因),因此您需要将其显式括在括号中(我还建议明确说明您传递的参数,尤其是在脚本中, 为了便于阅读):

Get-Content -Path ([OpPrj]::configFile)

枚举和静态 class 成员需要遵循此语法。


总计(您对 Out-String 的调用是不必要的):

class OpPrj
{
    [string] $ProjectPath

    static [string] $ConfigFile = 'settings.json'

    static [OpPrj] GetSettings()
    {
        return [OpPrj](Get-Content -Path ([OpPrj]::ConfigFile) -Raw | ConvertFrom-Json)
    }
}