2016-02-16 46 views
0

這是一個簡單的問題,但它一直讓我頭疼。我有一個很長的if條件,而不是寫在一行上,我想寫在多行清晰。跨越多行的長表達式

我做了一些研究,並設法找到使用& _,我可以在下一行寫下表達式。但是如果我寫的是這樣的:

If Not (DataGridView1.Rows(counter).Cells("User").Value Is Nothing) And & _ 
     (DataGridView1.Rows(counter).Cells("id number").Value Is Nothing) And & _ 
     (DataGridView1.Rows(counter).Cells("Emailaddress").Value Is Nothing) And & _ 
     (DataGridView1.Rows(counter).Cells("Date").Value Is Nothing) And & _ 
     (DataGridView1.Rows(counter).Cells("phone no.").Value Is Nothing) Then 

....... 'do something here' 
End If 

的問題是把And & _系統需要一個表達。我試着將& _移到其他位置,例如:在IS Nothing之前,但沒有運氣。

誰能幫我

+0

您使用的是什麼版本的VB.NET?或者,因爲它可能更容易回答,Visual Studio的版本是什麼?你可能不需要打擾續行字符。 –

+1

真的,它也適用,如果你只是刪除'&'或'&_'(VS2012)。 –

+0

考慮閱讀[文檔](https://msdn.microsoft.com/en-us/library/aa711641(v = vs.71).aspx) –

回答

3

And &部分肯定是不對的,獨立的換行符。你可以把整個混亂放在一行上(刪除所有的換行符),它仍然不能編譯。

VB.NET分別使用AndAndAlso作爲其位運算符和邏輯與運算符的名稱。 And具有按位語義,如C#中的&AndAlso具有邏輯和短路語義,如C#中的&&。您不應該(實際上不能)同時使用And&。而你應該在這裏使用AndAlso,因爲你需要邏輯,短路語義。

行尾的_字符用作續行字符。這是你在網上看到的,並且this is correct。你可以用它來將你的表情分成多行。

If Not (DataGridView1.Rows(counter).Cells("User").Value Is Nothing) AndAlso _ 
     (DataGridView1.Rows(counter).Cells("id number").Value Is Nothing) AndAlso _ 
     (DataGridView1.Rows(counter).Cells("Emailaddress").Value Is Nothing) AndAlso _ 
     (DataGridView1.Rows(counter).Cells("Date").Value Is Nothing) AndAlso _ 
     (DataGridView1.Rows(counter).Cells("phone no.").Value Is Nothing) Then 

....... 'do something here' 
End If 

但是,您可能不需要這樣做。如果您使用VB.NET的相對較新版本,implicit line continuation has been added to the language。任何運算符(如And)都將作爲隱式行連續運算符工作。所以你可以這樣做:

If Not (DataGridView1.Rows(counter).Cells("User").Value Is Nothing) AndAlso 
     (DataGridView1.Rows(counter).Cells("id number").Value Is Nothing) AndAlso 
     (DataGridView1.Rows(counter).Cells("Emailaddress").Value Is Nothing) AndAlso 
     (DataGridView1.Rows(counter).Cells("Date").Value Is Nothing) AndAlso 
     (DataGridView1.Rows(counter).Cells("phone no.").Value Is Nothing) Then 

....... 'do something here' 
End If 

就個人而言,我會強制排列列出於可讀性的目的。但我認爲VB.NET IDE會在這方面與你抗爭,所以它可能不值得。