创建您自己的集合类(CollectinBase的使用)

类别:软件工程 点击:0 评论:0 推荐:

通过从众多 .NET Framework 集合类之一继承,并添加实现您自己的自定义功能的代码,可以创建您自己的集合类。在本主题中,您将使用继承来创建一个从 CollectionBase 继承的简单的强类型集合。

.NET Framework 在 System.Collections 命名空间中提供了若干集合类型的类。其中有些类(如 StackQueue Dictionary)是已经实现以完成特定任务的专用类。而有些类(如 CollectionBaseDictionaryBase)则是已经具有某些基本功能,但将大部分实现工作都留给开发人员完成的 MustInherit (abstract) 类。

CollectionBase 类已经具有 Clear 方法和 Count 属性的实现,它维护一个称为 List Protected 属性,并将该属性用于内部存储和组织。其他方法(如 AddRemove)以及 Item 属性需要实现。

在该演练中,您使用 CollectionBase 类创建一个称为 WidgetCollection 的类。它是一个只接受小部件的集合,并且将其成员作为 Widget 类型公开,而不是接受对象并将成员作为 Object 类型公开。您然后实现将小部件添加到集合中和移除适当索引处的小部件的方法,您还实现 Item 属性以返回适当索引处的小部件对象。

创建类

第一步是创建要放入到 WidgetCollection 中的 Widget 类。

创建 Widget 类

' Visual Basic
Public Class Widget
   Public Name as String
End Class

创建 WidgetCollection 类


' Visual Basic
Public Class WidgetCollection
   Inherits System.Collections.CollectionBase
End Class

实现 Add 和 Remove 方法

现在您将实现 Add 方法,以便 WidgetCollection 只添加 Widget 对象。

 ' Restricts to Widget types, items that can be added to the collection.
Public Sub Add(ByVal awidget As Widget)
   ' Invokes Add method of the List object to add a widget.
   List.Add(aWidget)
End Sub

在该方法中,您将通过 Add 方法所带的参数添加到 List 对象中的项限制为 Widget 类型。尽管 List 对象可以接受任何类型的对象,但该方法禁止添加 Widget 类型以外的任何对象,并充当 List 对象的“包装”。

现在您有了将小部件添加到集合中的方法。您现在必须实现移除这些小部件的方法。通过与创建 Add 方法类似的方式来做到这一点,创建一个接受索引作为参数并反过来调用 List.RemoveAt 方法的 Remove 方法。

实现 Remove 方法

' Visual Basic
Public Sub Remove(ByVal index as Integer)
   ' Check to see if there is a widget at the supplied index.
   If index > Count - 1 Or index < 0 Then
      ' If no widget exists, a messagebox is shown and the operation is
      ' cancelled.
      System.Windows.Forms.MessageBox.Show("Index not valid!")
   Else
   ' Invokes the RemoveAt method of the List object.
      List.RemoveAt(index)
   End If
End Sub

该方法接受整数值作为索引参数。如果该值有效,它将被传递给 List 对象的 RemoveAt 方法,从而从集合中移除位于所指示的索引处的项。

为完成基本的集合功能,您需要实现最后一部分,即 Item 属性。Item 属性使您可以通过引用索引获取集合中某一对象的引用。鉴于您已经具有将成员添加到集合的 Add 方法,在该演示中,Item 将为 ReadOnly 属性,但在其他上下文中不必如此。由于 C# 不允许属性带参数,所以如果使用的是 C# 则需要将 Item 作为方法实现。

实现 Item 属性

' This line declares the Item property as ReadOnly, and
' declares that it will return a Widget object.
Public ReadOnly Property Item(ByVal index as Integer) As Widget
   Get
      ' The appropriate item is retrieved from the List object and
      ' explicitly cast to the Widget type, then returned to the
      ' caller.
      Return CType(List.Item(index), Widget)
   End Get
End Property

在集合中,语法 Collection.Item(0) 和 Collection(0) 经常可以互换。如果希望集合支持该语法,则应使 Item 属性成为 Default 属性(在 Visual Basic 中)或实现索引器(在 C# 中)。有关详细信息,请参见

本文地址:http://com.8s8s.com/it/it34897.htm