1

我正在使用 Visual Studio 2012 并具有以下代码块。该代码检查特定文件的文件类型(这就是其中返回 True/False 的原因)。如果遇到错误,它也会返回 false。我得到的警告是我在初始化之前使用了 fs/br 变量,这是真的。这就是为什么我有 IsNothing 语句,但我在 IsNothing 语句中收到警告,我不知道如何避免这种情况,因为我不想将fs = New FileStream(fn, FileMode.Open)andbr = ...语句放在 Try/Catch 块之外。

代码本身有效,因此警告并不是真正的问题,但拥有它们仍然让我感到困扰。有没有人看到解决方案如何更改此块以在没有警告的情况下提供相同的安全性?

欢迎 VB.NET 或 C# 答案。

            Dim fs As FileStream
            Dim br As BinaryReader
            Try
                fs = New FileStream(fn, FileMode.Open) 'Open the file
                br = New BinaryReader(fs) 'Initilize the reader
                'File reading code omitted here
                br.Close() 'Close the reader and underlying stream
            Catch
                If Not IsNothing(fs) Then fs.Close() 'Warning here
                If Not IsNothing(br) Then br.Close() 'and here
                Return False
            End Try
4

2 回答 2

2

这就是为什么我有 IsNothing 声明

这表明您希望这些值在被赋予特定值之前是 IsNothing。在 C# 中,这不仅仅是一个警告——这将是一个错误。

我有两个建议:

  • 如果您真的想遵循这种模式,只需将值设置为Nothing

    Dim fs As FileStream = Nothing
    Dim br As BinaryReader = Nothing
    
  • 如果可能的话,重新组织你的代码,这样你就可以使用Using语句来代替,这将关闭块末尾的流。不过,我们目前无法充分了解其余代码来帮助您做到这一点。
于 2014-02-05T13:02:59.063 回答
1

您可以重新编写它而不必使用嵌套的 Using 块-您可以在一行中完成所有操作-我不相信您可以在 C# 中执行此操作:

    Try
        Using fs As New FileStream(fn, FileMode.Open), br As New BinaryReader(fs)
            Try

            Catch ex As Exception
                'an exception here indicates an issue reading the file
            End Try
        End Using
    Catch ex As Exception
        'an exception here indicates an issue opening the filestream or reader
    End Try

using 块确保对象被处理掉,而无需显式调用.Dispose它也调用.Close,因此您甚至不需要该行

于 2014-02-05T15:15:56.527 回答