3

我正在尝试在 Powershell v5 中定义一个类,但我无法从类函数中访问变量。

前任。

PS C:\> class Foo{
          $bar = 'foobar'
          mymethod(){
            $bar + '123'
          }
        }
PS C:\> [Foo]::new().mymethod()
PS C:\> At line:4 char:11
        +           $bar + '123'
        Variable is not assigned in the method.
4

1 回答 1

7

用于$this访问您的变量:

class Foo{
      $bar = 'foobar'
      [string] mymethod(){
        return $this.bar + '123'
      }
    }

输出:

foobar123
于 2016-01-30T02:22:28.267 回答