下一个代码适用于我的,但我不知道这是否是最好的方法。在这种方式中,我需要写:_Button1=Button1和_MyVar=MyVar当参数传递给类构造函数的还有更多。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim myVar As String = "My children"
Dim NewClass1 As New Class1(Button1, myVar)
'... do more ...
End Sub
End Class
Public Class Class1
Private WithEvents _Button1 As Button
Private _MyVar As String
Public Sub New(ByVal Button1 As Button, ByVal MyVar As String)
_Button1 = Button1
_MyVar = MyVar
'... do more ...
End Sub
Private Sub _Button1_Click(sender As Object, e As EventArgs) _
Handles _Button1.Click
MsgBox("Button1 clicked and I love: " & _MyVar)
End Sub
End Class
_Button1=Button1和_MyVar=MyVar当传递给类构造函数的参数更多时,这种方法似乎重复且漫长。
这实际上是依赖注入,通常是一件好事。如果你最终得到了太多的构造函数参数,那么这应该是一个线索,表明你的类做了太多事情,违反了SOLID原则。
但是,您的Class1
不应该依赖于Form1
,而应该相反。您的代码可能更简单:
Public Class Class1
Friend Sub DoSomething(ByVal MyVar As String)
MsgBox(MyVar)
End Sub
End Class
Public Class Form1
Public Property class1() As Class1
Sub New()
InitializeComponent()
Me.class1 = New Class1()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
class1.DoSomething("blah, blah")
End Sub
End Class
虽然我没有在这里演示依赖项注入(为了简单起见),但您可以看到Class1
只知道它可以做一些工作,它根本不知道Form。
你可以在Class1
中订阅按钮点击事件,而不是将按钮传递给它。这会更干净,但设计仍然很糟糕。