0

我有两个带有相同按钮的表单,我想要它,这样如果我单击按钮,两个按钮都会做同样的事情,即它们在不同的表单上相互引用。我发现的方法是:

Public Class Form2
 Dim form1 As New form1
  Private Sub Button2_Click
   form1.backcolor=black
   form2.backcolor=black
 end sub
end class

然后

Public Class Form1
 Dim form2 As New form2
  Private Sub Button1_Click
   form1.backcolor=black
   form2.backcolor=black
 end sub
end class

只有这不起作用,因为有一个错误:An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll据我所知,没有无限循环或堆栈溢出。任何帮助将不胜感激。

4

2 回答 2

4

您有一个无限循环,因为每次实例化一种形式时,都会实例化另一种形式。创建一个Form1将创建一个Form2,然后Form2立即创建另一个Form1,依此类推……

将您的代码更改为:

Public Class Form2
   Private Sub Button2_Click
       Dim form1 As New Form1
       form1.backcolor=black
       form2.backcolor=black
   End sub
End class

Public Class Form1
    Private Sub Button1_Click
        form1.backcolor=black
        Dim form2 As New Form2
        form2.backcolor=black
    End sub
End class

现在它只会在您单击按钮时创建其他类实例。

于 2013-07-11T18:39:40.123 回答
0

正如 Karl Anderson 所说,您的代码中有一个无限循环。每次单击按钮时,他的解决方案都会创建一个新表单。如果您不想要这种行为,我认为最好的方法是使用中介模式。如果你想添加新的动作和新的表单,它会容易得多。

代码将如下所示:

Public Class Mediator
    Private forms As New List(Of BaseForm)

    Public Sub RegisterForm(form As BaseForm)
        forms.Add(form)
    End Sub

    Public Sub ChangeAllFormsBackColorToBlack()
        For Each form In forms
            form.ChangeBackColorToBlack()
        Next
    End Sub
End Class

Public Class BaseForm
    Private med As Mediator

    Public Sub New(med As Mediator)
        Me.med = med
        Me.med.RegisterForm(Me)
    End Sub

    Public Sub ChangeBackColorToBlack()
        backcolor = black
    End Sub

    Public Sub OnButtonClick()
        Me.med.ChangeAllFormsBackColorToBlack()
    End Sub
End Class

Public Class Form2
    Inherits BaseForm

    Public Sub New(med As Mediator)
        MyBase.New(med)
    End Sub

    Private Sub Button2_Click()
        Me.OnButtonClick()
    End Sub
End Class

Public Class Form1
    Inherits BaseForm

    Public Sub New(med As Mediator)
        MyBase.New(med)
    End Sub

    Private Sub Button1_Click()
        Me.OnButtonClick()
    End Sub
End Class

Module MediatorDemo
    Sub Main()
        Dim med As New Mediator
        Dim f1 As New Form1(med)
        Dim f2 As New Form2(med)

        f1.OnButtonClick()
    End Sub
End Module
于 2013-07-19T10:39:38.147 回答