类销毁时不会破坏类中的VB.NET表单

时间:2014-04-19 20:27:06

标签: vb.net forms class

我创建了一个应用程序。

主要形式是" Form1"。

我在Form1中声明了一个类:

Public Class Form1

    Private _MyClass As Class1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        _MyClass = New Class1

    End Sub
End Class

Class1声明如下:

Public Class Class1

    Private f As Form2

    Public Sub New()

        f = New Form2
        f.Show()

    End Sub
End Class

当我单击主窗体上的Button1时,会创建_MyClass1并显示Form2。

现在当我第二次单击Button1时,我希望销毁_MyClass1并创建一个新的_MyClass1。

我希望第一个Form2消失,因为_MyClass1被销毁了。

我认为它只存在于_MyClass1中,并且由于_MyClass1被销毁,因此Form2也应该被卸载。

相反,我突然打开了两个Form2窗口。

我的想法在哪里出错了?

来自VB6,如果托管类被终止,我希望自动卸载一个表单。在VB.NET中也不是这样吗?

3 个答案:

答案 0 :(得分:1)

您可以使用:

Public Class Form1

    Private _MyClass As Class1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

         If Not _MyClass Is Nothing Then ' To check if Class is initialized, If so then Close the Class or form
        _MyClass.close()
         End If
        _MyClass = New Class1

    End Sub
End Class

Public Class Class1

        Private f As Form2

        Public Sub New()

            f = New Form2
            f.Text = "form2"
            f.Show()

        End Sub
        Public Sub close()
            f.Close()
            Me.Finalize() ' Call Destructor 
        End Sub
    End Class

答案 1 :(得分:1)

您在表单内的私有类中有一个私有表单。 IDisposable恰好是用于创建其他一次性对象的类(表单是类)(CA会告诉您何时有代码创建的东西没有正确处理,就像2个3个俄罗斯套娃一样):

Public Class Class1
Implements IDisposable

Private f As Form2

Public Sub New()
    f = New Form2
    f.Text = "form2"
    f.Show()
End Sub

Private disposedValue As Boolean ' To detect redundant calls

' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
    If Not Me.disposedValue Then
        If disposing Then
            If f IsNot Nothing Then
                f.Close()           ' or f.Dispose
            End If 
        End If
    End If
    Me.disposedValue = True
End Sub

' VS generated code
Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
End Sub

End Class

对Form1.Designer.vb进行一次调整(CA会告诉你):

Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
            _MyClass.Dispose()             '  dispose of your toys
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

点击按钮:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' depending on what the point is, this will work:
    If _MyClass Is Nothing Then 
        _MyClass = New Class1
    End If

   ' if you really need it start anew:
   ' If _MyClass IsNot Nothing Then 
   '      _MyClass.Dispose
   ' End If 
   ' _MyClass = New Class1


End Sub

答案 2 :(得分:0)

再次点击按钮时。它不会破坏类的Previous对象。
每次单击按钮时,都会为class1创建一个新的实例或对象。