枚举和名称限定 (Visual Basic)Enumerations and Name Qualification (Visual Basic)

通常,在引用枚举成员时,必须使用枚举名称限定成员名称。Normally, when referring to a member of an enumeration, you must qualify the member name with the enumeration name. 例如,若要引用 Days 枚举的 Sunday 成员,请使用以下语法:For example, to refer to the Sunday member of your Days enumeration, you would use the following syntax:

X = Days.Sunday

使用 Imports 语句Using the Imports Statement

可以通过将 Imports 语句添加到代码的命名空间声明部分来避免使用完全限定的名称,如以下示例中所示:You can avoid using fully qualified names by adding an Imports statement to the namespace declarations section of your code, as in the following example:

Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays

Imports 语句从引用的项目和程序集中导入命名空间名称,并从与该语句所在模块相同的项目中导入命名空间名称。An Imports statement imports namespace names from referenced projects and assemblies and from within the same project as the module in which the statement appears. 添加此语句后,无需限定即可引用枚举成员,如以下示例中所示:Once this statement is added, you can refer to your enumeration members without qualification, as in the following example:

X = Sunday

通过组织枚举中的相关常量集,可以在不同的上下文中使用相同的常量名称。By organizing sets of related constants in enumerations, you can use the same constant names in different contexts. 例如,您可以对 Days 中的 weekday 常量和 WorkDays 枚举使用相同的名称。For example, you can use the same names for the weekday constants in the Days and WorkDays enumerations. 如果对枚举使用 Imports 语句,则必须小心,以避免不明确的引用。If you use the Imports statement with your enumerations, you must be careful to avoid ambiguous references. 请看下面的示例:Consider the following example:

Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays
Public Sub New()
  ' Insert code to implement constructor.
  X = Monday
End Sub

假定 MondayDays 枚举和 Workdays 枚举的成员,则此代码将生成编译器错误。Assuming that Monday is a member of both the Days enumeration and the Workdays enumeration, this code generates a compiler error. 若要避免引用单个常量时出现不明确的引用,请使用其枚举来限定常量名称。To avoid ambiguous references when referring to an individual constant, qualify the constant name with its enumeration. 以下代码引用 DaysWorkDays 枚举中的 Saturday 常量。The following code refers to the Saturday constants in the Days and WorkDays enumerations.

X = Days.Saturday
Y = WorkDays.Saturday

另请参阅See also