全局变量功能更改无效 [英] Global variable changed in function not effective

查看:126
本文介绍了全局变量功能更改无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚尝试了这段代码:

I just tried this code:

$m=2
function f
{
    $m=3
}
f
$m

我希望函数f会将$m更改为3.但是实际输出仍然是2.为什么? $m是全局变量,在f内不有效吗?

I expected that function f would change $m to 3. But the real output is still 2. Why? $m is a global variable, isn't it effective inside f?

推荐答案

否,恐怕PowerShell并非以这种方式设计.您必须考虑scopes,有关此主题的更多信息,请阅读PowerShell帮助

No, I'm afraid PowerShell isn't designed that way. You have to think in scopes, for more information on this topic please read the PowerShell help about scopes or type Get-Help about_scopes in your PowerShell ISE/Console.

简短的答案是,如果要更改全局范围内的变量,则应处理全局范围:

The short answer is that if you want to change a variable that is in the global scope, you should address the global scope:

$Number = 2

Function Foo {
    $Global:Number = 3
}
Foo
$Number

Function内部创建的所有变量在函数外部均不可见,除非您将其明确定义为ScriptGlobal.最佳做法是将函数的结果保存在另一个变量中,以便可以在脚本作用域中使用它:

All the variables created inside the Function are not visible outside the function, unless you explicitly defined them as Script or Global. It's best practice to save the result of a function in another variable, so you can use it in the script scope:

$Number = 5

Function Foo {
     $Number * 10
}
$Result = Foo

# Now you can use the value outside the function:
"The result of the function was '$Result'"

这篇关于全局变量功能更改无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆