你会如何在VB.NET中写这篇文章

本文关键字:文章 NET VB | 更新日期: 2023-09-27 17:59:17

我从来没有真正学习过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

不,转换器不工作,我已经试过了。

你会如何在VB.NET中写这篇文章

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

如果你能忍受一个带有"Exit-Do"的无条件循环,你可以避免额外的"ReadLine"语句——只说明选项:

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

这应该使用的经典模式

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

这种方法的好处是只需要一个guard语句,尽管您需要有两个ReadLine语句。

就我个人而言,Telerik建议的InlineAssignHelper是一个糟糕的模式,它只会让你的代码变得不清楚。

如果您担心代码的可读性,那么在您的情况下,使用纯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 Vincent)

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