为什么 powershell class 属性在他们的方法中需要这个?

Why do powershell class properties require this within their methods?

PS 版本:5.1.17134.858

我还没有用 Powershell 的 类 做很多工作,但这是我 运行 正在研究的一个简单示例:

class xNode{
   [uint64]$MyID=0
   static [uint64]$ClassID=0

   xNode(){
      $MyID = [xNode]::ClassID++
   }

   [String] ToString(){return "xNode: $MyID"}
}

不解析它给出了两个错误:
line 6 $MyID..., "Cannot assign property, use '$this.MyID'."
line 9 ..$MyID", "Variable is not assigned in the method."

我正在尝试使用名为$MyID的类属性,这种用法似乎与帮助文档get-help about_Classes中给出的示例一致,当我在最后将他们的整个示例复制到一个文件中然后尝试 运行 时,我也遇到了与 $Head$Body$Title 相同的错误,... 当然我可以通过添加 this.

来强制它工作
class xNode{
   [uint64]$MyID=0
   static [uint64]$ClassID=0

   xNode(){
      $this.MyID = [xNode]::ClassID++
   }

   [String] ToString(){return "xNode: $($this.MyID)"}
}

但是我不想一直在整个地方输入 this.,是否有一些环境设置或我忽略的东西?

(注意:为了让它在命令行下工作,我还需要删除所有空白行)

However I'd rather not have to keep typing this. all over the place, is there maybe some environment setting or something I've overlooked?

不,它像宣传的那样工作,如果没有 $this 变量引用,您不能在 class 中引用实例属性。

Why do powershell class properties require this within their methods?

(以下是我所说的"qualified speculation",即不是官方来源的解释)

PowerShell classes 从实施者的角度来看有点 tricky,因为 .NET 属性 的行为与参数不同在 powershell 脚本块或常规变量中。

这意味着当语言引擎解析、分析和编译构成您的 PowerShell Class 的代码时,必须格外注意哪些规则和约束适用于其中任何一个。

通过要求所有 "instance-plumbing" 通过 $this 路由,class 成员遵守一组规则与其他所有规则的问题范围变得更小,现有的编辑器工具可以继续(某种程度上)工作,只需很少的改动。

从用户的角度来看,要求 $this 还有助于防止意外事故,例如在创建新局部变量时覆盖实例成员。