在组件中添加以下代码。
' Visual Basic
Default Public ReadOnly Property Item(ByVal Index As Integer) As _
System.Windows.Forms.Button
Get
Return CType(Me.List.Item(Index), System.Windows.Forms.Button)
End Get
End Property
// C#
public System.Windows.Forms.Button this [int Index]
{
get
{
return (System.Windows.Forms.Button) this.List[Index];
}
}
实现 Remove 方法
您已经创建了公开数组中的按钮所需的属性,现在可以实现从数组中删除按钮的机制。要从数组中删除按钮,必须从集合的内部 List 对象和窗体的 Controls 集合中将其删除。
实现 Remove 方法
在组件中添加以下方法。
' Visual Basic
Public Sub Remove()
' 检查以确保存在要删除的按钮。
If Me.Count > 0 Then
' 从宿主窗体控件集合中删除添加到数组
' 的最后一个按钮。请注意在访问数组时
' 默认属性的使用。
HostForm.Controls.Remove(Me(Me.Count -1))
Me.List.RemoveAt(Me.Count -1)
End If
End Sub
在组件中添加以下方法。
' Visual Basic
Public Sub ClickHandler(ByVal sender As Object, ByVal e As _
System.EventArgs)
MessageBox.Show("您已单击按钮 " & CType(CType(sender, _
Button).Tag, String))
End Sub
// C#
public void ClickHandler(Object sender, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("您已单击按钮 " +
(string)((System.Windows.Forms.Button) sender).Tag);
}
此方法显示一个消息框,通过检索存储在按钮的 Tag 属性中的索引来指示单击了什么按钮。注意,此方法的签名与它将要处理的事件的签名相同,这是事件处理程序所要求的。
在类声明中,指定此类是从 .NET 框架的 System.Collections.CollectionBase 类继承而来的。
' Visual Basic
Public Class ButtonArray
Inherits System.Collections.CollectionBase
End Class
// C#
public class ButtonArray : System.Collections.CollectionBase
{
// 省略了由设计器添加的代码。
}
System.Collections.CollectionBase 类提供集合所需的许多功能。其中包括 List 对象(跟踪集合所包含的对象)、Count 属性(维护当前集合中的对象总数)和 RemoveAt 方法(按特定索引删除对象)。在实现控件数组集合时,要用到这些功能。
// C# 伪代码
myControl[myIndex].myProperty = myValue;
myControl[myIndex + 1].myMethod
使用单个事件处理程序处理多个控件的事件,检索并使用这些事件中的索引,如下例所示:
' Visual Basic 伪代码
Private Sub MyControl_Click(sender as Object, e as EventArgs)
Messagebox.Show("您已单击 MyControl 编号" & _
MyControl.Index)
End Sub
// C# 伪代码
private void myControl_Click(System.Object sender, System.EventArgs e)
{
Messagebox.Show("您已单击 MyControl 编号" +
MyControl.Index);
}
在运行时动态添加或删除控件,如下所示:
' Visual Basic 伪代码
Dim i as Integer
For i = 1 to 5
' 插入代码以创建控件并为属性分配值。
Next i
// C# 伪代码
for (int i = 1; i < 6; i++)
{
// 插入代码以创建控件并为属性分配值。
}