如何通过字符串从其他项目/程序集打开表单?

时间:2018-09-12 13:13:28

标签: vb.net .net-assembly

如何通过字符串从不同的项目/程序集中打开表单?

在一个解决方案中我有很多项目
例如:

  1. SalePurchase:具有:FrmSale,FrmPurchase,FrmMRN等...
  2. FAS:具有:FrmPayment,FrmReceipt等...
  3. 等...

我想从FAS.FrmPayment项目中打开SalePurchase

位于SalePurchase中的功能下方

Public Shared Function CreateForm(ByVal formName As String) As Form
    Return DirectCast(CreateObjectInstance(formName), Form)
End Function

Public Shared Function CreateObjectInstance(ByVal objectName As String) As _
Object
    Dim obj As Object : Dim ObjName As String = objectName
    Try
        If objectName.LastIndexOf(".") = -1 Then
            objectName = [Assembly].GetExecutingAssembly.GetName.Name & "." & objectName
        End If
        obj = [Assembly].GetExecutingAssembly.CreateInstance(objectName)
    Catch ex As Exception
        obj = Nothing
    End Try : Return obj
End Function

我运行SalePurchase项目

当我通过String=FrmSale时,效果很好

Dim FrmOpen As Form : FrmOpen =CreateForm(FrmSale)
FrmOpen.MdiParent = parent : FrmOpen.Show() : FrmOpen.Focus()

‘In this case obj has value {SalePurchase.FrmSale}

我通过String=FrmPayment时引发错误Object Reference not set to an Instance of an object

Dim FrmOpen As Form : FrmOpen =CreateForm(FrmPayment)
FrmOpen.MdiParent = parent : FrmOpen.Show() : FrmOpen.Focus()
‘In this case obj has value Nothing

Dim FrmOpen As New FrmPayment 'use direct object
FrmOpen.MdiParent = parent : FrmOpen.Show() : FrmOpen.Focus()
‘This is work fine

如何通过传递字符串打开FrmPayment

0 个答案:

没有答案