【问题标题】:How to declare a variable for using it into multiple IF如何声明一个变量以将其用于多个 IF
【发布时间】:2016-01-12 10:49:35
【问题描述】:

我想知道一次(在 If-then-else 循环之外)或多次(在每种情况下)声明变量之间的相关区别:

第一种情况(我正在使用这种方式):

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

有什么理由更改​​我的代码吗?

我的选择是否正确?

编辑

我更喜欢第一个,因为它更具可读性(至少对我而言)

编辑 2

好的,我想我可以在史蒂夫发布的链接中找到答案:

最小化范围

一般来说,在声明任何变量或常量时,它是好的 编程实践使范围尽可能窄(块 范围最窄)。这有助于节省内存并最大限度地减少 您的代码错误地引用错误变量的可能性。 同样,您应该将变量声明为静态 (Visual Basic) 仅当有必要在程序之间保持其价值时 来电。

【问题讨论】:

  • 你想在 if 结束后使用那个 YNC 吗?我想是的吧?然后尝试在 ifs 中多次声明它。 Scopes in Visual Basic
  • @Steve 有可能。我有多个 msgbox 问题。感谢您的链接,但我知道范围限制。我的问题是:什么更好,为什么?

标签: vb.net variables variable-declaration


【解决方案1】:

这取决于您是否需要进一步使用该值来控制程序流。

如果您再次需要该值,您别无选择,只能先声明它,否则它将超出范围。

“资源”方面的差异非常小(如果有的话),不值得担心。

【讨论】:

  • 在可读性和代码质量方面值得担心
【解决方案2】:

在这两种情况下,无论如何都会生成变量,如果考虑到代码的更好的可读性,情况2会很好。

这也导致了 IF 之后的变量范围,所以你也可以在 IF 之后使用它..

在我看来,CASE 2 对开发人员来说会更好(因为它不会影响系统并为进一步的更改提供更好的代码可读性和可理解性)。

【讨论】:

    【解决方案3】:

    差异出现在您发布的代码之后。

    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
    
    ' YNC doesn't exists here
    

    .

    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
    
    ' YNC does exists and you can use it
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      相关资源
      最近更新 更多