为什么直接访问静态会失败,但间接访问却可以?请注意,加载的文件在两个示例中都是有效的。
使用 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)
您需要遵循枚举和静态类成员的语法。
总而言之(不需要调用 Out-String
):
class OpPrj
{
[string] $ProjectPath
static [string] $ConfigFile = 'settings.json'
static [OpPrj] GetSettings()
{
return [OpPrj](Get-Content -Path ([OpPrj]::ConfigFile) -Raw | ConvertFrom-Json)
}
}
关于powershell - 在 Powershell 类中的静态方法中引用静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144278/