用于实现抽象的基类

更新:2007 年 11 月

用于实现抽象的基类是设计用于帮助开发人员实现抽象类和接口(抽象)的类。这些基类为抽象提供了一些实现细节,在某些情况下不用继承就可以使用它们。例如,可以使用 Collection<T> 创建一个集合,也可以从其进行继承以定义强类型集合类。

下面的代码示例演示如何使用 Collection<T> 类创建一个强类型集合对象。

Public Class PointManager
    Implements IEnumerable

    Private pointCollection As Collection(Of Point) = New Collection(Of Point)

    Public Sub AddPoint(ByVal p As Point)
        pointCollection.Add(p)
    End Sub

    Public Function RemovePoint(ByVal p As Point) As Boolean
        Return pointCollection.Remove(p)
    End Function

    Public Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        Return pointCollection.GetEnumerator
    End Function
End Class
public class PointManager : IEnumerable
{
    Collection<Point> pointCollection = new Collection<Point>();

    public void AddPoint(Point p)
    {
        pointCollection.Add(p);
    }
    public bool RemovePoint(Point p)
    {
        return pointCollection.Remove(p);
    }
    public IEnumerator GetEnumerator()
    {
        return pointCollection.GetEnumerator();
    }
}

下面的代码示例演示如何使用 Collection<T> 类定义一个强类型集合。

Public Class PointCollection
    Inherits Collection(Of Point)
End Class
public class PointCollection : Collection<Point> {}

CollectionBase 类是 .NET Framework 基类的另一个示例。该类可帮助开发人员实现非泛型集合。与 Collection<T> 不同的是,CollectionBase 不能直接使用。

只有用于实现抽象的基类能为使用库的开发人员带来很大价值时,才应将这些基类作为库的一部分予以提供。如果某一基类只用于帮助实现库,则该基类不应是公共可见的。若要在内部使用基类来简化库开发工作,公共成员应将工作委托给该基类,而不是从该基类继承。

如果基类设计用于公共 API 中,则在命名时避免为基类使用 Base 后缀。

如果库将基类作为返回类型或参数类型公开,则该基类不应带有 Base 后缀。

部分版权所有 2005 Microsoft Corporation。保留所有权利。

部分版权所有 Addison-Wesley Corporation。保留所有权利。

有关设计指南的更多信息,请参见 Krzysztof Cwalina 和 Brad Abrams 编著、Addison-Wesley 于 2005 年出版的“Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries”(《框架设计指南:可重用 .NET 库的约定、术语和模式》)。

请参见

其他资源

类库开发的设计准则

扩展性设计