类型设计准则Type Design Guidelines

就 CLR 而言,它仅支持两种类型 — 引用类型和值类型。但出于探讨框架设计的目的,我们将类型划分为多个逻辑组,每种都有其特定的设计规则。From the CLR perspective, there are only two categories of types—reference types and value types—but for the purpose of a discussion about framework design, we divide types into more logical groups, each with its own specific design rules.

类是使用最普遍的引用类型。Classes are the general case of reference types. 多数框架中的大部分引用类型都是类。They make up the bulk of types in the majority of frameworks. 类的广泛应用主要得益于其支持丰富的面向对象功能,以及普适性。Classes owe their popularity to the rich set of object-oriented features they support and to their general applicability. 基类和抽象类是具备扩展性的特殊逻辑组。Base classes and abstract classes are special logical groups related to extensibility.

接口也是一种类型。Interfaces are types that can be implemented by both reference types and value types. 接口可以被引用类型和值类型实现,因此可以充当这两种类型多态层次结构的根。They can thus serve as roots of polymorphic hierarchies of reference types and value types. 此外,接口也可用于模拟多个继承,而 CLR 本身并不支持该功能。In addition, interfaces can be used to simulate multiple inheritance, which is not natively supported by the CLR.

结构是常见的值类型。结构应当用来定义类似于语言基元的小型简单类型。Structs are the general case of value types and should be reserved for small, simple types, similar to language primitives.

枚举是一种特殊的值类型,它适用于定义一组数量有限的值,例如一周七天的名称、控制台颜色等。Enums are a special case of value types used to define short sets of values, such as days of the week, console colors, and so on.

静态类的作用是为静态成员提供容器。Static classes are types intended to be containers for static members. 它们通常用来为其他操作提供快捷方式。They are commonly used to provide shortcuts to other operations.

委托、异常、属性、数组和集合是适用于特定用途的特殊引用类型。关于这些类型的设计准则与使用情况将在本书其他章节中进行讨论。Delegates, exceptions, attributes, arrays, and collections are all special cases of reference types intended for specific uses, and guidelines for their design and usage are discussed elsewhere in this book.

✓ DO 确保每个类型定义完善的一组相关成员,而不仅仅是随机的不相关的功能集合。✓ DO ensure that each type is a well-defined set of related members, not just a random collection of unrelated functionality.

本节内容In This Section

在类和结构之间选择Choosing Between Class and Struct
抽象类设计Abstract Class Design
静态类设计Static Class Design
接口设计Interface Design
结构设计Struct Design
枚举设计Enum Design
嵌套类型Nested Types
部分©2005,2009 Microsoft Corporation。保留所有权利。Portions © 2005, 2009 Microsoft Corporation. All rights reserved.

*在 Pearson Education, Inc. 授权下,由 Addison-Wesley Professional 作为 Microsoft Windows 开发系列的一部分再版自 Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition(Framework 设计准则:可重用 .NET 库的约定、惯例和模式第 2 版),由 Krzysztof Cwalina 和 Brad Abrams 发布于 2008 年 10 月 22 日。Reprinted by permission of Pearson Education, Inc. from Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition by Krzysztof Cwalina and Brad Abrams, published Oct 22, 2008 by Addison-Wesley Professional as part of the Microsoft Windows Development Series.

另请参阅See also