编译器警告:null引用异常

Rob*_*obS 6 vb.net visual-studio-2005

我在Visual Studio 2005中有以下代码.

    Dim OutFile As System.IO.StreamWriter
    Try
        OutFile = New System.IO.StreamWriter(Filename)
       // Do stuff with OutFile
    Catch Ex As Exception
       // Handle Exception
    Finally
       If OutFile IsNot Nothing Then OutFile.Close()
    End Try
Run Code Online (Sandbox Code Playgroud)

但VS2005提出警告"If OutFile IsNot .."这一行

变量'OutFile'在被赋值之前使用.在运行时可能会导致空引用异常.

有没有办法通过巧妙地改变代码来消除这个警告,或者只是有更好的方法来做我正在尝试做的事情?

谢谢

tva*_*son 10

Dim OutFile As System.IO.StreamWriter
OutFile = Nothing
Try
    OutFile = New System.IO.StreamWriter(Filename)
   // Do stuff with OutFile
Catch Ex As Exception
   // Handle Exception
Finally
   If OutFile IsNot Nothing Then OutFile.Close()
End Try
Run Code Online (Sandbox Code Playgroud)

C#错误类似:使用未分配的局部变量

  • 并不是的.它不是试图阻止空引用,而是意外省略默认值.强制您显式提供默认值以删除警告,这会让您意识到您已将变量放在未定义的位置. (2认同)