新表单 "is never disposed" 消息

New form "is never disposed" message

我最近搬到了 Visual Studio 2019 V16.2,现在每当我在我的 Windows 表单应用程序中切换表单时,它都会向我显示一个新的 "message"。

IDE0067 Disposable object created by 'New FindFile' is never disposed

我总是在我的项目中使用 "next" 形式,代码片段如下:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim frmFindFile As New FindFile
    frmFindFile.Show()
    Me.Close()

End Sub

我做错了什么?一旦显示新变量,我是否应该处理 form 变量?下面去掉了警告,但我的第二个表格从未出现!

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim frmFindFile As New FindFile
    frmFindFile.Show()
    Me.Close()
    frmFindFile.Dispose()
End Sub

VB.NET 有默认的表单实例,所以如果你只是使用 FindFile.Show() 它不会给出警告。

有关详细信息,请参阅 Why is there a default instance of every form in VB.Net but not in C#?

中的答案

我还没有看到这个问题的正确答案,但是有一个。

上面列出的原代码是:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim frmFindFile As New FindFile
    frmFindFile.Show()
    Me.Close()

End Sub

然而,正确的方法是:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Using frmFindFile As FindFile = New FindFile()
        frmFindFile.Show()
    End Using
    Me.Close()

End Sub

这将自动处理 Using 结构中需要处理的任何内容。

几乎所有可以使用 Dim/As class 结构实例化的东西都可以放在 Using 结构中。

另一个例子是使用 streamreader/writer。使用 Using 实例化它,然后不使用 instance.Close(),只需使用 End Using 关闭它并处理它。