我正在尝试编写一个函数,该函数返回由输入指定的新创建的对象(表单)。我遇到了如何计算出一个类型作为输入的概念然后在函数体中创建该类型的对象的问题。以下是我正在研究的内容概述。
Public Function MakeMyForm(ByVal frmType as Form) as Form
Dim NewObj as New frmType
Return NewObj
End Function
我希望能够以这种方式调用该函数:
Dim myform as CustomFormType
myform = MakeMyForm(CustomFormType)
我的概念可以在VB.net中完成吗?
答案 0 :(得分:2)
好的,如果我了解你,你只需要一个通用的方法:
Public Function MakeMyForm(Of T As {New, Form})() As T
Return New T()
End Function
并将其称为:
Dim myform As CustomFormType = MakeMyForm(Of CustomFormType)()
当然,为什么你不会使用:
Dim myform As New CustomFormType()
答案 1 :(得分:0)
你可以试试这个:
Dim frmnew() As Form
Dim createdforms As Integer = 0
Private Sub createform(wintext As String, height As Integer, width As Integer, backcolor As Color, topmost As Boolean, formborderstyle As FormBorderStyle, winstate As FormWindowState, opacity As Decimal, startposition As FormStartPosition, enabled As Boolean) 'add as many properties as you like
ReDim Preserve frmnew(createdforms)
frmnew(createdforms) = New Form
With frmnew(createdforms)
.Text = wintext
.Height = height
.Width = width
.BackColor = backcolor
.TopMost = topmost
.FormBorderStyle = formborderstyle
.WindowState = winstate
.Opacity = opacity
.StartPosition = startposition
.Enabled = enabled
End With
frmnew(createdforms).Show()
createdforms += 1
End Sub
您可以使用以下代码进行测试:
createform("Afnan Makhdoom", 500, 700, Color.Aqua, False, Windows.Forms.FormBorderStyle.Fixed3D, FormWindowState.Normal, 0.9, FormStartPosition.CenterScreen, True)
答案 2 :(得分:0)
Public Function Makemyform(ByVal frmType As Form) As Form
Dim obj As Form
obj = newfunc(frmType)
Return obj
End Function
Public Function newfunc(ByVal mytype As Form) As Form
Return New Form
End Function
答案 3 :(得分:0)
这通常使用泛型来完成,例如:
Public Function GetItem(Of T)(key As String) As T
用法:
myIntVar = myFoo.GetItem(Of Int32)(bar)
其目的是让代码调用它来指定它需要返回的方式。在上面,一大堆数据已被序列化并且原始类型丢失,因此在取回时,Of T
有助于转换它,而不是使用Object
作为返回。
对于表单,它更成问题:
Public Function MakeAForm(Of T)() As Form ' cant do As T
您必须添加更多代码才能将Form转换为Form1或frmCust以避免tbName is not a member of System.Windows.Forms.Form
错误。即使Dokjnas先生所显示的正确方法也存在试图用以下形式做更多事情的问题:
Public Function MakeAForm(Of T As {New, Form})() As T
Dim frm As New T
If frm.GetType Is frm8088.GetType Then
frm.textbox1.text = "ziggy" ' error
End If
Return frm
这里,'TextBox不是T`的成员。如果您的表单已编译为ClassLib,那么IDE可以了解有关类型(表单)的更多信息,您可以使其工作。但是使用它时显示出徒劳的第一个迹象:
Dim frm As Form = MakeAForm(Of frm8100VI)()
frm.Show()
调用FormMaker需要的代码多于创建实例所需的代码。