Vb.net 错误地使用IIF
这个按钮的宽度是123。为什么下面的内容不改变它的宽度Vb.net 错误地使用IIF,vb.net,Vb.net,这个按钮的宽度是123。为什么下面的内容不改变它的宽度 Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click With Me.Button3 IIf(.Width = 123, .Width = 233, .Width = 150) End With End Sub IIF只是返回一个值吗?i、 e如果
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
With Me.Button3
IIf(.Width = 123, .Width = 233, .Width = 150)
End With
End Sub
IIF只是返回一个值吗?i、 e如果我想设置按钮的宽度属性,那么我是否需要使用if结构
您的代码测试
.Width=123
,然后返回布尔表达式.Width=233
(如果为真)或.Width=150
(如果为假),然后丢弃结果。这不是你想要的。你有三种选择:
' IIf function - not recommended since it is not typesafe and evaluates all arguments.
.Width = IIf(.Width = 123, 233, 150)
' If operator - typesafe and only evaluates arguments as necessary.
.Width = If(.Width = 123, 233, 150)
' If statement - not an expression.
If .Width = 123 Then .Width = 233 Else .Width = 150
您的代码测试
.Width=123
,然后返回布尔表达式.Width=233
(如果为真)或.Width=150
(如果为假),然后丢弃结果。这不是你想要的。你有三种选择:
' IIf function - not recommended since it is not typesafe and evaluates all arguments.
.Width = IIf(.Width = 123, 233, 150)
' If operator - typesafe and only evaluates arguments as necessary.
.Width = If(.Width = 123, 233, 150)
' If statement - not an expression.
If .Width = 123 Then .Width = 233 Else .Width = 150
使用VB.NEt的If()-语句。它被称为“条件运算符”,存在于多种语言中。IIf是一个特定于VB的函数,具有不同的行为。
更多信息请点击此处:
在这两种情况下,IIf和If只返回一个值(IIf的值不是类型化的;它是一个必须强制转换的对象)。不管怎样,它似乎做了你想要的事情:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Button3.Width = If(Button3.Width = 123, 233, 150)
End Sub
使用VB.NEt的If()-语句。它被称为“条件运算符”,存在于多种语言中。IIf是一个特定于VB的函数,具有不同的行为。
更多信息请点击此处:
在这两种情况下,IIf和If只返回一个值(IIf的值不是类型化的;它是一个必须强制转换的对象)。不管怎样,它似乎做了你想要的事情:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Button3.Width = If(Button3.Width = 123, 233, 150)
End Sub
IIF只是返回一个值吗
对
i、 e如果我想设置按钮的宽度属性,那么我是否需要使用if结构
否,因为您可以将返回值指定给Width
属性:
With Me.Button3
.Width = IIf(.Width = 123, 233, 150)
End With
请注意,在当前版本的VB.NET中,应使用而不是Iif,因为它具有多种优点(类型安全、短路等)。例如,使用If(…)
将允许您的代码在编译时无需额外强制转换,即使您对选项有严格要求(您应该这样做)
IIF只是返回一个值吗
对
i、 e如果我想设置按钮的宽度属性,那么我是否需要使用if结构
否,因为您可以将返回值指定给Width
属性:
With Me.Button3
.Width = IIf(.Width = 123, 233, 150)
End With
请注意,在当前版本的VB.NET中,应使用而不是Iif,因为它具有多种优点(类型安全、短路等)。例如,使用If(…)
将允许您的代码在编译时无需额外强制转换,即使您对选项有严格要求(您应该这样做)
好的-但是VB中没有与C相比的=
,那么comiler是如何决定.Width=233
是一个布尔表达式而不是我试图设置属性的呢?这取决于上下文=
被解释为赋值运算符,但表达式中的=
被解释为相等运算符。+1谢谢。所以IIf
是一个表达式
,而如果不是一个表达式
,而是一个操作符
?我已经在我的答案中添加了应该澄清问题的内容。好吧-但是与C相比,VB中没有=
,那么comiler是如何确定.Width=233
是一个布尔表达式而不是布尔表达式的呢我是否尝试设置属性?这取决于上下文=
被解释为赋值运算符,但表达式中的=
被解释为相等运算符。+1谢谢。所以IIf
是一个表达式
,而If
不是一个表达式
,而是一个操作符
?我在我的答案中添加了应该澄清问题的内容。好吧-我假设VB的选项Strict On
的功能等同于VBA的选项Explicit
?@whytheq:No,VB的选项显式
相当于VBA的选项显式
。它不允许隐式转换。好的-我假设VB的选项Strict On
的功能等同于VBA的选项Explicit
?@whytheq:不,VB的选项Explicit
等同于VBA的选项Explicit
。它不允许隐式转换。