我想知道是否存在使用 Type 作为表达式的技巧,例如在此代码中:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ControlType = CheckBox ' CheckBox is a type and cannot be used as an expression
Dim ControlArray(5) As ControlType ' (5) The number of controls to create.
For num As Int64 = 0 To ControlArray.LongLength - 1
ControlArray(num) = New ControlType ' Expected: New CheckBox
ControlArray(num).Text = (ControlType.ToString & num.ToString) ' Expected string: "CheckBox 0"
Me.Controls.Add(ControlArray(num))
Next
End Sub
我不是在问我如何做一个控件数组,我是在问我是否可以做一个通用控件数组,例如在 var (ControlType) 中指定类型并像上面的代码示例一样使用它。
更新
这是我现在尝试使用的代码
尝试附加处理程序时,我无法识别 CheckBox 的“CheckedChanged”事件
尝试检查其值时也无法识别“.Checked”属性。
Public Class Form1
Dim ControlType As Type = GetType(CheckBox) ' The type of Control to create.
Dim ControlArray(5) As Control ' (5) The number of controls to create.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For num As Int64 = 0 To ControlArray.LongLength - 1
ControlArray(num) = Activator.CreateInstance(ControlType) ' Create the control instance (New CheckBox)
ControlArray(num).Name = ControlType.Name & num.ToString ' Name example : CheckBox 0
ControlArray(num).Text = ControlType.Name & num.ToString ' String example: CheckBox 0
ControlArray(num).Top = 20 * num ' Adjust the location of each control.
Me.Controls.Add(ControlArray(num)) ' Add the control to a container.
' This does not work:
AddHandler ControlArray(num).CheckedChanged, AddressOf CheckBoxSub ' Add a event handler to a procedure.
Next
End Sub
Public Sub CheckBoxSub(ByVal sender As Object, ByVal e As System.EventArgs) ' Sub which is handling the controls.
If sender.Checked = True Then MsgBox(sender.name & " is checked") Else MsgBox(sender.name & " is unchecked")
' Just an example of how to use the controls,
' This does not work:
ControlArray(2).checked = True ' CheckBox 2.Checked = True
End Sub
End Class