2012-07-11 127 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