为什么我不能在 Powershell 5 的函数中访问 class 变量?
Why can't I access class variables in function in Powershell 5?
我试图在 Powershell v5 中定义一个 class,但我无法从 class 函数中访问变量。
例如
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.
使用$this
访问您的变量:
class Foo{
$bar = 'foobar'
[string] mymethod(){
return $this.bar + '123'
}
}
输出:
foobar123
我试图在 Powershell v5 中定义一个 class,但我无法从 class 函数中访问变量。
例如
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.
使用$this
访问您的变量:
class Foo{
$bar = 'foobar'
[string] mymethod(){
return $this.bar + '123'
}
}
输出:
foobar123