Powershell类中静态方法中的引用静态成员

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

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

使用直接静态失败

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);
  }
powershell class properties static powershell-v5.0
1个回答
1
投票

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

Get-Content [OpPrj]::configFile

PowerShell解析器无法确定结束的位置(我不确定原因),因此您需要将其明确地包装在括号中(我还建议明确说明您传递的参数,特别是在脚本中,以提高可读性):

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

您需要为枚举和静态类成员遵循此语法。


总之(你不需要调用Out-String):

class OpPrj
{
    [string] $ProjectPath

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

    static [OpPrj] GetSettings()
    {
        return [OpPrj](Get-Content -Path ([OpPrj]::ConfigFile) -Raw | ConvertFrom-Json)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.