2016-07-28 45 views
0

我從來沒有真正學過VB.NET,你會如何在VB.NET中編寫它?你會如何在VB.NET中寫這個?

下面是代碼:

System.IO.StreamReader file = new System.IO.StreamReader(ofd_tracking_file.FileName); 
while ((line = file.ReadLine()) != null) 
{ 
} 

難道是這樣嗎?

Dim file As System.IO.StreamReader = New System.IO.StreamReader(ofd_tracking_file.FileName) 

While Not line = file.ReadLine() = Nothing  
End While 

不,轉換器不工作,我已經嘗試過。

+1

你嘗試了嗎?它編譯了嗎?它運行正確嗎?此外,代碼似乎轉換罰款在這裏http://converter.telerik.com/ – DavidG

+0

我不知道InlineAssignHelper是什麼? –

+0

我在這裏找到了我的答案:http://www.c-sharpcorner.com/forums/inlineassignhelper –

回答

1

C#代碼使用表達式內的分配 - 這些在VB中不可用。 VB的等效是:

Dim file As New System.IO.StreamReader(ofd_tracking_file.FileName) 
line = file.ReadLine() 
Do While line IsNot Nothing 
    ... 
    line = file.ReadLine() 
Loop 

可避免額外「的ReadLine」語句,如果你能忍受與一個「退出做」無條件循環 - 只是陳述選項:

Do 
    line = file.ReadLine() 
    If line Is Nothing Then Exit Do 
    ... 
Loop 
0

這應該做使用經典模式的伎倆:

Dim file As New System.IO.StreamReader(ofd_tracking_file.FileName) 

Dim line = file.ReadLine() 
While line IsNot Nothing 
    'blah blah 
    line = file.ReadLine() 
End While 

這種方法的好處是,只有一個後衛的語句是必需的,但你必須有兩個ReadLine陳述。

個人而言,Telerik建議的InlineAssignHelper是一個不好的模式,它只是讓你的代碼不清楚。

+0

@sstan感謝編輯,我無法弄清楚爲什麼它不能識別語言的權利:) – MickyD

+1

這是因爲在這個特定的問題中,C#標記超過了VB.NET標記。發生這種情況時,您需要明確設置語法突出顯示的語言。 – sstan

0

如果您擔心您的代碼可讀性,那麼在您的情況下使用純粹vb.net代碼將是更好的選擇。

Using reader As New StreamReader(ofd_tracking_file.FileName) 
    Dim line As String = Nothing 
    Do 
     line = reader.ReadLine() 
     Debug.Write(line) 
    Loop Until line Is Nothing 
End Using 

或使用EndOfStream財產將在我看來更具有可讀性(感謝@Visual文森特)

Using reader As New StreamReader(ofd_tracking_file.FileName) 
    While reader.EndOfStream = false 
     Dim line As String = reader.ReadLine() 
     'use line value 
    End While 
End Using 
+0

您的第一個示例將不起作用 - 當線條最終變爲'Nothing'時,您在'循環直到'條件被檢查之前使用它,所以您將獲得空引用異常。 –

+0

@DaveDoknjas,如果使用line可以處理'null'值,它將工作。但你是對的,第一個例子將需要額外的檢查。我添加了第一個示例,因爲「Loop Until line Is Nothing」部分是可讀性的很好例子:) – Fabio