何时使用枚举 (Visual Basic)When to Use an Enumeration (Visual Basic)

枚举提供了使用相关常量集的简单方法。Enumerations offer an easy way to work with sets of related constants. 一个枚举,或Enum,是一组值的符号名称。An enumeration, or Enum, is a symbolic name for a set of values. 枚举被视为数据类型,并可用于创建用变量和属性使用的常数的集。Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

何时使用枚举When to Use an Enumeration

当一个过程接受一组有限的变量时,请考虑使用一个枚举。Whenever a procedure accepts a limited set of variables, consider using an enumeration. 枚举可使更明确且更具可读性的代码,尤其是在使用有意义的名称时。Enumerations make for clearer and more readable code, particularly when meaningful names are used.

使用枚举的优点包括:The benefits of using enumerations include:

  • 这样可以减少错误引起的转置或键入数字。Reduces errors caused by transposing or mistyping numbers.

  • 便于将来更改值。Makes it easy to change values in the future.

  • 使代码易于阅读,这意味着它不太可能的错误将蔓延到其中。Makes code easier to read, which means it is less likely that errors will creep into it.

  • 可确保向前兼容性。Ensures forward compatibility. 借助枚举、 你的代码是不太可能会失败,如果有人在将来更改的成员名称与对应的值。With enumerations, your code is less likely to fail if in the future someone changes the values corresponding to the member names.

命名枚举Naming Enumerations

枚举成员使用的命名约定。Use a naming convention for enumeration members. 当 Visual Basic 遇到的枚举成员名称时,如果其他引用的类型库包含相同的名称可能会引发异常。When Visual Basic encounters an enumeration member name, an exception may be thrown if other referenced type libraries contain the same name. 使用唯一的前缀,用于标识您的应用程序或组件中的值。Use a unique prefix that identifies the values from your application or component.

当引用枚举成员,必须限定为枚举名称的成员名称,否则使用Imports语句。When referring to a member of an enumeration, you must qualify the member name with the enumeration name or else use the Imports statement. 有关详细信息,请参阅枚举和名称限定For more information, see Enumerations and Name Qualification.

预定义的枚举Predefined Enumerations

Visual Basic 提供了大量预定义的枚举,如FirstDayOfWeekMsgBoxResult,以便于您的代码。Visual Basic provides a number of predefined enumerations, such as FirstDayOfWeek and MsgBoxResult, to facilitate your code. 有关这些列表请参阅常量和枚举For a list of these see Constants and Enumerations.

请参阅See also