vb.net 带有布尔条件的 If 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29234568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If Statement with Boolean Condition
提问by JonW
I've got some really simple code in visual studio that, for whatever reason, is not working. I've narrowed the problem down to my boolean condition in the if statement. Here is a simplified version:
我在visual studio中有一些非常简单的代码,无论出于何种原因,它们都不起作用。我已将问题缩小到 if 语句中的布尔条件。这是一个简化版本:
Dim bool As boolean
Protected Sub Button1Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If bool = true Then
bool = false
ElseIf bool = false Then
bool = true
End If
Label1.Text = bool
End Sub
This is within a button click event. If bool is initially set to true, when I click it, it goes to false, but then if I click it again the "bool = false" statement is not executed.
这是在按钮单击事件中。如果 bool 最初设置为 true,当我单击它时,它会变为 false,但是如果我再次单击它,则不会执行“bool = false”语句。
Edit: As asked, the full button click handler has been added to the code above. As asked, this is for an asp.net website. The point of this code is to, on a button click, change the style of a header element on a button click. However, this has no effect on the question, as I took that code out temporarily to reduce any potential problems and was left with the code above.
编辑:如所问,完整的按钮单击处理程序已添加到上面的代码中。正如所问,这是一个asp.net 网站。这段代码的重点是,在单击按钮时,在单击按钮时更改标题元素的样式。但是,这对问题没有影响,因为我暂时删除了该代码以减少任何潜在问题,并保留了上面的代码。
回答by rageandqq
It seems like all you're doing is toggling the value of the boolean flag.
Assuming it is always either trueor false, you can just invert the value:
似乎您所做的只是切换布尔标志的值。
假设它始终是trueor false,您可以反转该值:
booleanVar = Not booleanVar
回答by Georg Jung
The code you posted should obviously be working, taken by itself. Your problem might be that the value of boolis not saved between different web requests. You need to save that value. Try using the HttpContext's Sessionproperty like this:
您发布的代码显然应该可以正常工作,可以单独使用。您的问题可能是bool不同的 Web 请求之间没有保存的值。您需要保存该值。尝试像这样使用HttpContext的Session属性:
Dim bool as Boolean
If Session.Item("bool") Is Nothing Then
Session("bool") = True
End If
bool = DirectCast(Session("bool"), Boolean)
For more information see the MSDN Session State Overviewand the linked "How to" articles about session information here.
有关更多信息,请参阅MSDN 会话状态概述和此处链接的有关会话信息的“操作方法”文章。
Edit: For making your code more readable and to not clutter your click event handler you can write the following to methods:
编辑:为了使您的代码更具可读性并且不会使您的点击事件处理程序混乱,您可以将以下内容写入方法:
Private Function GetBoolValue() as Boolean
If Session.Item("bool") Is Nothing Then
Session("bool") = True
End If
Return DirectCast(Session("bool"), Boolean)
End Function
Private Sub SetBoolValue(value as Boolean)
Session("bool") = value
End Sub

