我如何称呼通用Of T
子选择表单字符串?
如何更好地编写这样的代码?
Sub ShowAddfrm(Of T As {Form, New})()
dim frm as new T 'New Form
frm.Show()
End Sub
Private Sub btnAddProblemfrm_Click(sender As Object, e As EventArgs)
Dim keys As String = CType(sender, Button).Name.Replace("btnAdd", "")
If keys = "frmShowProblem" Then
ShowAddfrm(Of frmShowProblem)()
End If
If keys = "frmUser" Then
ShowAddfrm(Of frmUser)()
End If
End Sub
答案 0 :(得分:0)
尝试此重载方法,同时允许Form引用和字符串参数。
您可以传递表单的默认实例,直接将其命名:
ShowAddfrm(Form2)
或表单名称:
ShowAddfrm("Form2")
或在事件处理程序中使用控件的Tag
属性(或任何其他源):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ShowAddfrm(DirectCast(sender, Control).Tag.ToString())
End Sub
有所不同:
string 版本使用Activator.CreateInstance使用其名称来生成Form的新实例。
Sub ShowAddfrm(Of T As {Form, New})(ByVal form As T)
form.Show()
End Sub
Sub ShowAddfrm(formName As String)
Dim appNameSpace = Assembly.GetExecutingAssembly().GetName().Name
Dim form = CType(Activator.CreateInstance(Type.GetType($"{appNameSpace}.{formName}")), Form)
ShowAddfrm(form)
End Sub