2012-07-11 137 views
1

非常简单的问题,如何结合和或运营商到相同的陈述。vb.net结合和或或运营商

c.GetType是的getType(文本框)和Foo或酒吧或巴兹

这是行不通的

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 

感谢,我是。网新手!

+0

你得到什么错误?第一个陈述对我来说很好 – Luis 2012-07-11 22:03:32

+0

@ LuisSchechez:第一个语句等同于'If(c.GetType是GetType(TextBox))和True Then'。 – Heinzi 2012-07-11 22:14:23

+0

@Heinzi事实上,我在那里看到和'='而不是'<>' – Luis 2012-07-11 22:23:37

回答

2

顺便说一句,你可以使用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只返回给定类型的控制,在这种情况下,文本框
  • Where由过滤控制Name property(note:And and AndAlso difference
  • For Each迭代产生的结果IEnumerable(Of TextBox)
+0

完美,谢谢! – dan 2012-07-11 22:19:59

1

从数学的角度来看,您的第一个说法没有任何意义。表达

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 

逻辑上等同的。

(我也冒昧改变你的类型检查,以更优雅的变体和和/或与他们更有效的同行进行更换。)

+0

我想你错过了一个开放的'(''在第一个例子之后的'And'... – Luis 2012-07-11 22:14:34

+0

@ LuisSanchez:谢谢,我决定删除'''而不是。 – Heinzi 2012-07-11 22:15:11