我有一个事件,我必须实例化一个表单:
Private Sub ParametresEtablissement(ByRef frmmain As Form, ByRef frmparametablissement As Form, ByRef OpenedForms As FormCollection, ByVal TypeOfFrmEtablissement As Type)
If (frmparametablissement Is Nothing) Then
frmparametablissement = New TypeOfFrmEtablissement
frmparametablissement.MdiParent = frmmain
frmparametablissement.Show()
Else
End Sub
但我在这一行中有错误:
frmparametablissement = New TypeOfFrmEtablissement
错误为Type TypeOfFrmEtablissement is not defined
所以我需要知道:
答案 0 :(得分:2)
什么是TypeOfFrmEtablissement
?它有默认构造函数吗?
您可能需要查看Activator.CreateInstance。您可以将对象类型作为参数传入,它将使用该类型的默认构造函数返回实例。
Dim instance As IExample = DirectCast(Activator.CreateInstance(theType), IExample)
您也可以查看Generics来创建对象,但我认为这对您的要求来说太过分了。
Public Function f(Of T)() As T
Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {})
Return tmp
End Function
更新关注Lamloumi的评论:
我创建了一个新项目添加了一个新表单(Form2),并从Form1构造函数中调用了它,并创建并显示了一个新的Form2实例。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim frmparametablissement As Form = CreateFormInstance(Form2)
frmparametablissement.Show()
End Sub
Private Function CreateFormInstance(Of T As Form)(type As T) As T
Return Activator.CreateInstance(GetType(T))
End Function