我希望在类方法中,我可以在方法内部设置“局部”变量,但事实并非如此。以下是测试代码:
class test_scope {
$var = "class var"
test_scope() {
}
[void] my_method() {
$var = "method var"
}
}
$obj = [test_scope]::new()
$obj.my_method()
我收到一条错误消息:
Line |
8 | $var = "method var"
| ~~~~
| Cannot assign property, use '$this.var'.
这是令人惊讶的。我怎样才能有局部变量?
作为比较,函数(即在类之外)可以具有与脚本变量同名的局部变量。下面是一个例子:
$var2="global var"
function my_function() {
$var2="function var"
write-host $var2
write-host $script:var2
}
my_function($null)
我得到了我期望的答案:
function var
global var
作为与 Python 的另一个比较:
class test_scope:
var = "class var"
def my_method(self):
var = "method var"
print(self.var)
print(var)
obj = test_scope()
obj.my_method()
它按预期工作:
function var
global var
所以 PowerShell 不正常?
PS:我在 PowerShell 5.0 和 7.0 下测试过。