你如何从另一个类中调用未知类型的方法

时间:2014-03-20 21:37:34

标签: vb.net-2010

VB.NET

有问题声明我的表单/类并使用单个参数传入方法指针但参数在编译时是未知类型。

最好在FooForm中声明和引发事件,从而通过公共属性公开所需的数据,或者通过将子指针作为委托传递来使用我在下面描述的方法。无论哪种方式只是为了我的经验,我想让这个工作。

我尝试使用(Of T)声明我的表单Class和Action(Of T)的参数,T是未知类型但是我不知道如何调用Action参数来调用我的方法。如果我想稍后添加其他操作,那么拥有我的FooForm的多个实例或继承会更加开销,因此将myAction声明为特定类型,与泛型类型相反。

例如:

Class AEventArgs
    Inherits EventArgs

    Public ReadOnly A As String

    Public Sub New(ByVal A As String)
        Me.A = A
    End Sub
End Class

Class BEventArgs
    Inherits EventArgs

    Public ReadOnly B As Integer

    Public Sub New(ByVal B As String)
        Me.B = B
    End Sub
End Class

Class FooForm(Of T As EventArgs)
    ...
    Private myAction As Action(Of T)

    Public Sub New(myAction As Action(Of T))
        Me.myAction = myAction
    End Sub

    Private Sub btnA_Click(sender As Object, e As System.EvetArgs) Handles btnA.Click
        Dim eA As New AEventArgs("aa")
        Me.myAction(eA)  'This does not compile because eA is not of type T
    End Sub

    Private Sub btnB_Click(sender As Object, e As System.EventArgs) Handles btnB.Click
        Dim eB As New BEventArgs("bb")
        Me.myAction(eB)  'This does not compile because eB is not of type T
    End Sub

End Class

Class MainForm
    ...
    Sub AFoo(A As AEventArgs)
       'Do Something with A
    End Sub

    Sub BFoo(B As BEventArgs)
        'Do Somthing with B
    End Sub

    Sub ActionA()
        Dim fooA As New FooForm(Of AEventArgs)(AddressOf AFoo)
        fooA.ShowDialog()
    End Sub

    Sub ActionB()
        Dim fooB As New FooForm(Of BEventArgs)(AddressOf BFoo)
        fooB.ShowDialog()
    End Sub
   ...
End Sub

任何帮助都会受到赞赏吗?

0 个答案:

没有答案