【问题标题】:How can I check if any of my boolean variable is false in VB.NET如何检查我的任何布尔变量在 VB.NET 中是否为假
【发布时间】:2019-10-15 18:26:50
【问题描述】:

请问这是在 VB.net 中检查变量是否为假的唯一方法吗?

这是我的代码

if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if

【问题讨论】:

  • 您需要提出您想要回答的实际问题。您的代码建议您要确定是否只有一个变量是 False 以及它是哪一个。是这样吗?如果不是,请准确描述实际情况。
  • @jmcilhinney 你说得对
  • 顺便说一句,您所做的在客观上并没有错,但是使用If a And b And Not c Then 而不是If a = True And b = True And c = False Then 更正确。使用AndAlsoOrElse 而不是AndOr 也更合适,除非您特别需要短路,这种情况很少见。
  • 这仍然取决于具体情况,因为您似乎不太可能真正向用户显示变量名称。确定一个值列表是否包含与另一个值完全匹配的值很容易,并且确定该匹配的索引也很容易,但是获取该值的原始变量名称是另一回事,但它会很奇怪首先需要。
  • @jmcilhinney 我只想检查我创建的代码是否是唯一可以检查三个布尔变量中是否包含错误的代码。而已!我继续使用它作为我的代码,但在我看来它有点乱。

标签: vb.net


【解决方案1】:

更多的是代码审查部分,但无论如何我都会给出答案......

为了我的审美,写If (a = True) ThenIf (a = False) Then是丑陋的,我宁愿使用If (a) ThenIf (Not a) Then

在您的代码中,如果 a + b 有错误,则不会发生任何事情,因为这种情况不会被处理。劳斯莱斯的实现可能如下所示:

Public Class Application

    Public Sub DoSomething()
        '... get the results from 3 calls to other methods
        Dim a As Boolean = MethodA()
        Dim b As Boolean = MethodB()
        Dim c As Boolean = MethodC()
        Dim myErrors As String = GetErrorMessage(a, b, c)
        If (myErrors Is Nothing) Then
            MsgBox("ok")
        Else
            MsgBox(myErrors)
            Environment.Exit(-1)
        End If
    End Sub

    Private Function GetErrorMessage(a As Boolean, b As Boolean, c As Boolean) As String
        If (a AndAlso b AndAlso c) Then Return Nothing
        Dim myList As New List(Of String)(3)
        If (Not a) Then myList.Add(NameOf(MethodA))
        If (Not b) Then myList.Add(NameOf(MethodB))
        If (Not c) Then myList.Add(NameOf(MethodC))
        Select Case myList.Count
            Case 1
                Return $"{myList(0)} has errors!"
            Case 2
                Return $"{myList(0)} and {myList(1)} have errors!"
            Case Else
                Return $"{String.Join(", ", myList.Take(myList.Count - 1))} and {myList(myList.Count - 1)} have errros!"
        End Select
    End Function

    Private Function MethodA() As Boolean
        'Does something
        Return True
    End Function

    Private Function MethodB() As Boolean
        'Does something
        Return False
    End Function

    Private Function MethodC() As Boolean
        'Does something
        Return False
    End Function

End Class

作为一般建议,我不会从 3 个调用中返回布尔值,而是将它们实现为 Sub,如果出现问题则抛出异常,这样您就可以提供更准确的反馈并处理更高级别的错误如果您愿意,可以调用堆栈。以下是此类实现的示例:

Public Class Application

    Public Sub DoSomething()
        Dim myErrors As List(Of String) = Nothing
        Try
            MethodA()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(3)
            myErrors.Add($"{NameOf(MethodA)}: {ex.Message}")
        End Try
        Try
            MethodB()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(2)
            myErrors.Add($"{NameOf(MethodB)}: {ex.Message}")
        End Try
        Try
            MethodC()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(1)
            myErrors.Add($"{NameOf(MethodC)}: {ex.Message}")
        End Try
        If (myErrors Is Nothing) Then
            MsgBox("OK")
        Else
            MsgBox($"The following errors occurred:{vbCrLf}{vbCrLf}{String.Join(vbCrLf, myErrors)}")
        End If
    End Sub

    Private Sub MethodA()
        'Does something
    End Sub

    Private Sub MethodB()
        'Does something
        Throw New NotImplementedException()
    End Sub

    Private Sub MethodC()
        'Does something
        Throw New NotSupportedException()
    End Sub

End Class

【讨论】:

    【解决方案2】:

    我会检查每个布尔值然后存储错误(如果有)来解决它。

    Dim Report as String = ""
    
    If a = false Then
        Report = Report & vbCrlf & "a has errors"
    End If
    
    If b = false Then
        Report = Report & vbCrlf & "b has errors"
    End If
    
    If c = false Then
        Report = Report & vbCrlf & "c has errors"
    End If
    
    If Report = "" Then
        Msgbox("OK")
    Else
        Msgbox(Report)
    End If
    

    【讨论】:

      【解决方案3】:

      我的方法是将布尔值放入一个数组中。通过检查值 = False 的循环。 False 值的索引被添加到 lstIndexes。

          Dim lstIndexes As New List(Of Integer)
          Dim bools = {a, b, c}
          For i = 0 To bools.Length - 1
              If Not bools(i) Then
                  lstIndexes.Add(i)
              End If
          Next
      

      【讨论】:

        【解决方案4】:

        虽然我喜欢 Cristoph 的回答,但如果目标是抛出错误消息而不继续,那么你能不也这样做吗?

        Public Sub DoSomething(a as Boolean, b as Boolean, c as Boolean)
        
            If Not a Then
                MsgBox("A has errors!") ' Or have a log message or throw an exception.
                Exit Sub                ' Or Return Nothing if it's a function
            End If
        
            If Not b Then
                MsgBox("B has errors!") ' Or have a log message or throw an exception.
                Exit Sub                ' Or Return Nothing if it's a function
            End If
        
            If Not c Then
                MsgBox("C has errors!") ' Or have a log message or throw an exception.
                Exit Sub                ' Or Return Nothing if it's a function
            End If
        
            DoNextThing()
        
        End Sub
        

        【讨论】:

        • 是的,它可以工作,但是如果 a 和 b 有错误,只有消息“A 有错误!”由于Exit Sub 而显示。
        • 是的,这更像是在进行某种方法之前解决您的第一个问题。这在文件检查中很常见,例如,文件必须先存在才能进行其他任何操作。
        • 简单易读的小建议:Report &= "a has errors" & vbCrlf
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-31
        • 1970-01-01
        • 1970-01-01
        • 2019-04-07
        • 2016-05-07
        • 2014-11-17
        • 1970-01-01
        相关资源
        最近更新 更多