vb.net 的合并和或操作符

30 浏览
0 Comments

vb.net 的合并和或操作符

非常简单的问题,如何将and或or运算符组合在同一个语句中。

c.GetType是getType(TextBox)并且foo或bar或baz。

这不起作用。

For Each c As Control In Me.Controls
    If (c.GetType Is GetType(TextBox)) And ((c.Name <> "txtID") Or (c.Name <> "txtAltEmail")) Then
        'do something
    End If
Next

这个可以工作:

For Each c As Control In Me.Controls
    If (c.GetType Is GetType(TextBox)) And (c.Name <> "txtID") Then
        'do something
    End If
Next

谢谢,我是一个 .net 新手!

admin 更改状态以发布 2023年5月21日
0
0 Comments

从数学角度来看,你的第一句话是没有意义的。表达式

X <> A or X <> B

将始终返回true(在你的情况下,给定A <> B,它将被满足,因为"txtID" <> "txtAltEmail")。

(如果X = A,第二个子句将为真。如果X = B,第一个子句将为真。如果X是任何其他值,则两个子句都为真。)

你可能意味着写

If (TypeOf c Is TextBox) AndAlso (c.Name <> "txtID") AndAlso (c.Name <> "txtAltEmail") Then

If (TypeOf c Is TextBox) AndAlso Not ((c.Name = "txtID") OrElse (c.Name = "txtAltEmail")) Then

它们在逻辑上是等价的。

(我还自作主张地将你的类型检查更改为更优雅的变体,并用它们更有效的替代品替换了And/Or。)

0
0 Comments

顺便说一下,您可以使用LINQ来提高可读性:

Dim allTextBoxes = From txt In Me.Controls.OfType(Of TextBox)()
                  Where txt.Name <> "txtID" AndAlso txt.Name <> "txtAltEmail"
For Each txt In allTextBoxes
    ' do something with the TextBox '
Next

  • OfType仅返回指定类型的控件,本例中为TextBoxes
  • Where通过Name属性过滤控件(注意:VB.NET中AndAndAlso的区别
  • For Each迭代结果IEnumerable(Of TextBox)
0