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

时间:2019-03-13 14:27:39

标签: powershell class properties static powershell-v5.0

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

直接使用静态失败

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);
  }

1 个答案:

答案 0 :(得分: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)
    }
}