我想知道是否存在使用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)中指定Type并在代码中使用它上面的例子。
更新
这是我尝试使用
的代码我无法识别" CheckedChanged"尝试附加处理程序时CheckBox的事件
也无法识别" .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
答案 0 :(得分:1)
您可以使用System.Type来保存对象的类型。
您还可以使用Activator.CreateInstance(MyType)创建MyType类型对象的实例。
e.g。
Dim ControlType As System.Type = GetType(CheckBox)
Dim ControlArray(5) As Control
For num As Int64 = 0 To 5
ControlArray(num) = Activator.CreateInstance(ControlType)
ControlArray(num).Left = num * 100
ControlArray(num).Name = "CheckBox " & num
ControlArray(num).Text = ControlArray(num).Name
Me.Controls.Add(ControlArray(num))
Next
编辑:
要添加事件处理程序,您需要DirectCast()将Control转换为对象类型,例如:
AddHandler DirectCast(ControlArray(Num), CheckBox).CheckedChanged, AddressOf MyHandler
答案 1 :(得分:1)
关于您更新的问题:您需要将对象强制转换为正确的类型,以便能够使用特定于CheckBox的属性或事件。例如。而不是
AddHandler ControlArray(num).CheckedChanged, AddressOf CheckBoxSub
你写了
Dim cbx As CheckBox = TryCast(ControlArray(num), CheckBox)
If cbx IsNot Nothing Then
AddHandler cbx.CheckedChanged, AddressOf CheckBoxSub
End If
第二个例子相同:
Dim cbx As CheckBox = TryCast(ControlArray(2), CheckBox)
If cbx IsNot Nothing Then ' If the second control is a check box
cbx.Checked = True
End If
TryCast
将给定对象强制转换为给定类型,如果对象具有不同类型,则返回Nothing
。