VBScript 中变量的作用域 [英] Scope of a variable in VBScript
问题描述
考虑以下代码:
Option Explicit
Dim Count : Count = 4
'Case-I
Sub Display1()
MsgBox(Count)
End Sub
'Case-II
Sub Display2(Count)
MsgBox(Count)
End Sub
混乱
- 如果变量
Count
可以被两者访问method
还是只针对Display2
方法? - 如果变量
count
不能通过Display1
方法访问,那么有没有办法让它在任何子或函数中可用不将其传递给Sub
或Function
- 现在,如果我更新了
Display2
子中的Count
变量该值可用于其他function
或sub
,前提是VBScript 具有global
变量声明.
- here should the variable
Count
will be accessible to the bothmethod
or only to theDisplay2
method? - If the variable
count
is not accessible withDisplay1
method,then is there any way to make it useable within any sub or function without passing it to thatSub
orFunction
- Now if I updated the
Count
variable from theDisplay2
sub will that value can be used to otherfunction
orsub
provided that VBScript hasglobal
variable declarations.
推荐答案
变量 count
在任何函数或子过程之外声明,因此它的作用域在这里是全局的.全局变量可以在任何函数或子过程中使用,其值可以在程序流程的任何地方改变.
Variable count
is declared outside of any function or sub-procedure, hence its scope is global here. Global variable can be used in any function or sub-procedure and its value can be change in anywhere in program flow.
现在,如果您调用此过程并运行 .vbs 文件,则消息框将在两种情况下显示 4
.
Now if you make call to this procedure and run the .vbs file, message box will display 4
in both cases.
Option Explicit
Dim Count : Count = 4
'Case-I
Sub Display1()
MsgBox(Count)
End Sub
'Case-II
Sub Display2(Count)
MsgBox(Count)
End Sub
Call Display1()
Call Display2(Count)
如果你在任何函数或子过程中改变了count
变量的值,它的值也会随着其他过程的变化而改变,因为它的作用域是全局的.
If you change value of count
variable in any function or sub procedure, its value will change for other procedure also as its scope is global.
选项显式
Dim Count : Count = 4
'Case-I
Sub Display1()
Count = 5 ''value changed here
MsgBox(Count)
End Sub
'Case-II
Sub Display2(Count)
MsgBox(Count)
End Sub
Call Display1()
Call Display2(Count)
在上述情况下,两个消息框都会显示5
In above case, both message box will display 5
这篇关于VBScript 中变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!