我想知道一次声明变量(在If-then-else循环之外)或多次(在每种情况下)之间有什么区别:如何声明一个变量用于多个IF
第一种情况下(我使用这种方式):
If A < 0 Then
Dim YNC As MsgBoxResult = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
ElseIf A = 0 Then
Dim YNC As MsgBoxResult = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
Else
Dim YNC As MsgBoxResult = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
End If
第二种情况:
Dim YNC As MsgBoxResult
If A < 0 Then
YNC = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
ElseIf A = 0 Then
YNC = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
Else
YNC = MsgBox("Select Yes-No-Cancel", vbYesNoCancel, "Select")
'Some code
End If
有什么理由去改变我的代码?
我做了正确的选择吗?
编辑
我更喜欢第一个,因为它更可读的(至少对我来说)
EDIT 2
好吧,我觉得我得到我的回答到发布的史蒂夫链接:
最小化范围
一般来说,在声明任何变量或常数时,编程练习的好处是尽量缩小范围(块 的范围最窄)。这有助于节省内存,并最大限度地减少代码错误地引用错误变量的机会。 同样,只有在需要在过程 调用之间保留其值时,才应将变量声明为静态(Visual Basic) 。
你想在if后使用YNC吗?我想是的吧?然后尝试在ifs中多次声明它。 [Visual Basic中的范围](https://msdn.microsoft。com/en-us/library/1t0wsc67.aspx) – Steve
@Steve这是可能的。我有多个msgbox问题。感谢您的链接,但我知道范围限制。我的问题是:什么更好,为什么? – genespos