多种形式、实例并在 class 中使用它们。 VB.net

Multiple forms, instances and using them in a class. VB.net

我有一个 MDI 父窗体,它有多个窗体,声明为:

Partial Public Class Giriş

Private clients As thirdperson
Private suppliers As thirdperson
Private activecontrol As thirdperson
Private proposals As transactions
Private addproposal As addtransaction
private sales as transactions
private addsales as addtransation
Private products As products
...
...

我还有一个作为 class 工作的 dataworks sub,但我在表单中对它进行编码,并且对每个表单进行编码,如下所示: '例如按下添加新按钮

If ActiveControl Is **clients** Or ActiveControl Is **suppliers** Then
  activeform.dataworks (counter, "add new")
ElseIf ActiveControl Is products Then
  products.dataworks (counter, "add new")
ElseIf ActiveControl Is addproposal Then
  addproposal.dataworks (counter, "add new")
End If

我需要一种方法来弄清楚如何使用可变名称作为实例名称。 (我不想每次都定义每个实例名称,我只想知道是否有如下使用方法: '例如 变暗形式变量作为​​形式

formvariable.dataworks(counter,"add new") --> just want to use this and assign the value for products, proposals vs to this variable.

这可能吗?

提前感谢您的帮助。 Sertac.

正确的方法是开发一个 Interface 您的所有子窗体都实现的。该接口将有一个 dataworks() 方法。然后你可以将当前的 mdichild 转换为接口类型和 运行 方法。这将导致有意义的强类型编码。

不过,如果你只是想破解它,那么尝试使用反射从当前的 mdichild 中获取 dataworks() sub 并像下面这样执行它:

    Dim frm As Form = Me.ActiveMdiChild
    If Not IsNothing(frm) Then
        Dim MI As Reflection.MethodInfo = frm.GetType.GetMethod("dataworks", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.IgnoreCase)
        If Not IsNothing(MI) Then
            MI.Invoke(frm, New Object() {counter, "add new"})
        End If
    End If

下面是接口方法的一个简单示例:

Public Interface Data

    Sub DataWorks(ByVal counter As Integer, ByVal msg As String)

End Interface

这是第三人称实现界面的样子:

Public Class thirdperson
    Implements Data

    Public Sub DataWorks(counter As Integer, msg As String) Implements Data.DataWorks
        Debug.Print(counter & ", " & msg)
    End Sub

End Class

您的所有 mdichild 表格都必须以类似的方法进行修改。

那么MdiParent中的代码会变成:

    Dim frm As Form = Me.ActiveMdiChild
    If TypeOf frm Is Data Then
        Dim D As Data = DirectCast(frm, Data)
        D.DataWorks(counter, "add new")
    End If