vb.net 使用其他形式的函数

vb.net use function from other form

我的情况是,我只有一个助手 class,我在我的大部分表单上都重复使用了它。碰巧我的助手 class 也需要从该表单调用一个函数

Public Class Form1
   Dim hc As HelperClass

   Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm1Sub()
      'do something
   End Sub
End Class

Public Class Form2
   Dim hc As HelperClass

   Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm2Sub()
      'do something
   End Sub
End Class

Public Class Form3
   Dim hc As HelperClass

   Private Sub Form3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      hc = New HelperClass
   End Sub

   Private Sub someForm3Sub()
      'do something
   End Sub
End Class

Public Class HelperClass
   'i need to call here someForm1Sub(), someForm2Sub(), someForm3Sub()
   'but it bases on which form uses this class
End Class

我认为有很多方法可以做到这一点。我已经阅读了一些关于委托函数的内容,但我不知道如何将委托传递给其他 class。我正在使用 vb.net 2010。请提供执行此操作的最佳方法

请回复谢谢。

您可以使用 AddressOf 关键字将委托传递给方法。例如,

Public Sub Test()
    ' Make Foo() call the Bar() method.
    Foo(AddressOf Bar)
End Sub

Public Sub Foo(d As Action)
   ' Call the delegate.
   d()
End Sub

Public Sub Bar()
    Console.WriteLine("Bar was called.")
End Sub

但是,正如您所说,有很多方法可以做到这一点。一种可能比传递委托更好的解决方案(特别是如果表单中有一些方法可以由助手 class 调用)将 Form1, Form2Form3 都实现了一个接口,并让 HelperClass 在接口上调用一个方法。然后可以在其构造函数中将接口实例提供给 HelperClass

例如,

Public Interface IForm

    Sub DoStuff()

End Interface


Public Class Form2
    Implements IForm


    Dim hc As HelperClass


    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        hc = New HelperClass(Me)
    End Sub

    Public Sub DoStuff() Implements IForm.DoStuff
        ' Do stuff here.
    End Sub

End Class


Public Class HelperClass

    Private _form As IForm


    Public Sub New(form as IForm)
        _form = form
    End Sub


    Public Sub MakeTheFormDoStuff()
        _form.DoStuff()
    End Sub

End Class