Enum 陳述式 (Visual Basic)Enum Statement (Visual Basic)

宣告列舉,並定義其成員的值。Declares an enumeration and defines the values of its members.


[ <attributelist> ] [ accessmodifier ]  [ Shadows ]
Enum enumerationname [ As datatype ]
End Enum


  • attributelist

    選擇性。Optional. 這個列舉型別所套用的屬性清單。List of attributes that apply to this enumeration. 您必須將括屬性清單角括弧 ("<"和">")。You must enclose the attribute list in angle brackets ("<" and ">").

    FlagsAttribute屬性表示列舉型別的執行個體的值可以包含多個列舉成員,而且每個成員,代表在列舉值的位元欄位。The FlagsAttribute attribute indicates that the value of an instance of the enumeration can include multiple enumeration members, and that each member represents a bit field in the enumeration value.

  • accessmodifier

    選擇性。Optional. 指定哪些程式碼可以存取此列舉型別。Specifies what code can access this enumeration. 可以是下列其中一項:Can be one of the following:

  • Shadows

    選擇性。Optional. 指定此列舉型別重新宣告,並隱藏的名稱相同的程式設計項目或一組多載的項目,基底類別中。Specifies that this enumeration redeclares and hides an identically named programming element, or set of overloaded elements, in a base class. 您可以指定Shadows只在列舉型別本身,而不是在它的任何成員。You can specify Shadows only on the enumeration itself, not on any of its members.

  • enumerationname

    必要項。Required. 列舉型別的名稱。Name of the enumeration. 如需有效的名稱,請參閱宣告項目名稱For information on valid names, see Declared Element Names.

  • datatype

    選擇性。Optional. 列舉型別及其所有成員的資料型別。Data type of the enumeration and all its members.

  • memberlist

    必要項。Required. 此陳述式所宣告的成員常數的清單。List of member constants being declared in this statement. 多個成員會出現在個別的原始程式碼行。Multiple members appear on individual source code lines.

    每個member具有下列語法和組成部分: [<attribute list>] member name [ = initializer ]Each member has the following syntax and parts: [<attribute list>] member name [ = initializer ]

    組件Part 描述Description
    membername 必要項。Required. 這個成員的名稱。Name of this member.
    initializer 選擇性。Optional. 在編譯時期評估,以及指派給這個成員的運算式。Expression that is evaluated at compile time and assigned to this member.
  • End EnumEnd Enum

    終止 Enum 區塊。Terminates the Enum block.


如果您有一組彼此邏輯相關的不變值時,可以在列舉型別一起定義它們。If you have a set of unchanging values that are logically related to each other, you can define them together in an enumeration. 這會提供有意義的名稱,列舉型別和其成員,也就是容易記住它們的值。This provides meaningful names for the enumeration and its members, which are easier to remember than their values. 然後,您可以使用在許多地方列舉型別成員在您的程式碼。You can then use the enumeration members in many places in your code.

使用列舉的優點包括:The benefits of using enumerations include the following:

  • 減少調換,或輸入數字的錯誤所造成的錯誤。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 be introduced.

  • 可確保往後相容性。Ensures forward compatibility. 如果您使用列舉型別時,您的程式碼是比較不可能失敗,如果有人在未來變更為成員名稱的對應值。If you use enumerations, your code is less likely to fail if in the future someone changes the values corresponding to the member names.

列舉型別具有名稱、 基礎資料類型和一組的成員。An enumeration has a name, an underlying data type, and a set of members. 每一個成員代表的常數。Each member represents a constant.

在類別、 結構、 模組或介面層級,任何程序中,外部宣告的列舉型別是成員的列舉型別An enumeration declared at class, structure, module, or interface level, outside any procedure, is a member enumeration. 它是類別、 結構、 模組或介面會宣告它的成員。It is a member of the class, structure, module, or interface that declares it.

成員的列舉型別可以從任何位置內存取他們的類別、 結構、 模組或介面。Member enumerations can be accessed from anywhere within their class, structure, module, or interface. 程式碼類別之外,結構或模組必須限定成員列舉型別的名稱,該類別、 結構或模組的名稱。Code outside a class, structure, or module must qualify a member enumeration's name with the name of that class, structure, or module. 您可以避免需要使用完整限定的名稱加上匯入原始程式檔陳述式。You can avoid the need to use fully qualified names by adding an Imports statement to the source file.

在命名空間層級,任何類別、 結構、 模組或介面外部宣告的列舉型別是在出現的命名空間的成員。An enumeration declared at namespace level, outside any class, structure, module, or interface, is a member of the namespace in which it appears.

宣告內容列舉型別必須是原始程式檔、 命名空間、 類別、 結構、 模組或介面,並不是程序。The declaration context for an enumeration must be a source file, namespace, class, structure, module, or interface, and cannot be a procedure. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

您可以將屬性套用至整個列舉型別而非其成員個別。You can apply attributes to an enumeration as a whole, but not to its members individually. 屬性會提供資訊給組件的中繼資料。An attribute contributes information to the assembly's metadata.

資料類型Data Type

Enum陳述式可以宣告列舉的資料類型。The Enum statement can declare the data type of an enumeration. 每個成員會在列舉的資料類型。Each member takes the enumeration's data type. 您可以指定ByteIntegerLongSByteShortUIntegerULong,或UShortYou can specify Byte, Integer, Long, SByte, Short, UInteger, ULong, or UShort.

如果您未指定datatype列舉中,每個成員都會採用的資料型別其initializerIf you do not specify datatype for the enumeration, each member takes the data type of its initializer. 如果您同時指定datatypeinitializer的資料類型initializer必須可轉換成datatypeIf you specify both datatype and initializer, the data type of initializer must be convertible to datatype. 如果既未datatypeinitializer已存在,將資料類型會預設為IntegerIf neither datatype nor initializer is present, the data type defaults to Integer.

初始化成員Initializing Members

Enum陳述式可以初始化中的所選成員的內容memberlistThe Enum statement can initialize the contents of selected members in memberlist. 您使用initializer提供要指派給成員的運算式。You use initializer to supply an expression to be assigned to the member.

如果您未指定initializer成員,Visual Basic 將它初始化為零 (如果它是第一個membermemberlist),或值比前一大memberIf you do not specify initializer for a member, Visual Basic initializes it either to zero (if it is the first member in memberlist), or to a value greater by one than that of the immediately preceding member.

在每個所提供的運算式initializer可以是常值、 已定義,其他常數和列舉成員已定義,包括先前的成員,這個列舉型別的任何組合。The expression supplied in each initializer can be any combination of literals, other constants that are already defined, and enumeration members that are already defined, including a previous member of this enumeration. 您可以使用算術和邏輯運算子來結合這類項目。You can use arithmetic and logical operators to combine such elements.

您無法使用變數或函式中的initializerYou cannot use variables or functions in initializer. 不過,您可以使用轉換關鍵字這類CByteCShortHowever, you can use conversion keywords such as CByte and CShort. 您也可以使用AscW如果您呼叫它具有常數StringChar引數,因為,可以在編譯時期評估。You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at compile time.

列舉型別不能有浮點值。Enumerations cannot have floating-point values. 如果將成員指派為浮點數值和Option Strict設定為 on,就會發生編譯器錯誤。If a member is assigned a floating-point value and Option Strict is set to on, a compiler error occurs. 如果Option Strict已關閉,值會自動轉換為Enum型別。If Option Strict is off, the value is automatically converted to the Enum type.

如果成員的值超過允許的範圍為基礎的資料類型,或如果您初始化任何成員為基礎的資料類型所允許的最大值時,編譯器會回報錯誤。If the value of a member exceeds the allowable range for the underlying data type, or if you initialize any member to the maximum value allowed by the underlying data type, the compiler reports an error.


類別、 結構、 模組和介面成員列舉型別的預設值為公用存取。Class, structure, module, and interface member enumerations default to public access. 您可以調整它們的存取層級,使用存取修飾詞。You can adjust their access levels with the access modifiers. 命名空間成員列舉型別預設為 friend 存取權限。Namespace member enumerations default to friend access. 您可以調整其存取層級 public,但不是屬於私用或受保護。You can adjust their access levels to public, but not to private or protected. 如需詳細資訊,請參閱 < 存取 Visual Basic 中的層級For more information, see Access levels in Visual Basic.

所有的列舉型別成員具有公用存取,而且您無法使用任何存取修飾詞在其上。All enumeration members have public access, and you cannot use any access modifiers on them. 不過,如果列舉型別本身具有更具限制性的存取層級,指定的列舉存取層級會優先。However, if the enumeration itself has a more restricted access level, the specified enumeration access level takes precedence.

根據預設,所有列舉都是型別,而且其欄位都是常數。By default, all enumerations are types and their fields are constants. 因此SharedStatic,和ReadOnly宣告列舉型別或其成員時,就無法使用關鍵字。Therefore the Shared, Static, and ReadOnly keywords cannot be used when declaring an enumeration or its members.

指派多個值Assigning Multiple Values

列舉型別通常代表互斥的值。Enumerations typically represent mutually exclusive values. FlagsAttribute屬性中Enum宣告中,您可以改為將指派多個值給列舉型別的執行個體。By including the FlagsAttribute attribute in the Enum declaration, you can instead assign multiple values to an instance of the enumeration. FlagsAttribute屬性會指定列舉型別視為位元欄位,也就是一組旗標。The FlagsAttribute attribute specifies that the enumeration be treated as a bit field, that is, a set of flags. 這些稱為位元列舉型別。These are called bitwise enumerations.

當您使用宣告列舉FlagsAttribute屬性,我們建議您使用 2,可為、 1、 2、 4、 8、 16,並依此類推的次方的值。When you declare an enumeration by using the FlagsAttribute attribute, we recommend that you use powers of 2, that is, 1, 2, 4, 8, 16, and so on, for the values. 我們也建議 「 無 」 是的成員,其值為 0 的名稱。We also recommend that "None" be the name of a member whose value is 0. 如需其他指導方針,請參閱FlagsAttributeEnumFor additional guidelines, see FlagsAttribute and Enum.


下列範例顯示如何使用 Enum 陳述式。The following example shows how to use the Enum statement. 請注意,成員指EggSizeEnum.Medium,而不是MediumNote that the member is referred to as EggSizeEnum.Medium, and not as Medium.

Public Class Egg
    Enum EggSizeEnum
    End Enum

    Public Sub Poach()
        Dim size As EggSizeEnum

        size = EggSizeEnum.Medium
        ' Continue processing...
    End Sub
End Class


下列範例中的方法將會超出Egg類別。The method in the following example is outside the Egg class. 因此,EggSizeEnum完整限定為Egg.EggSizeEnumTherefore, EggSizeEnum is fully qualified as Egg.EggSizeEnum.

Public Sub Scramble(ByVal size As Egg.EggSizeEnum)
    ' Process for the three largest sizes.
    ' Throw an exception for any other size.
    Select Case size
        Case Egg.EggSizeEnum.Jumbo
            ' Process.
        Case Egg.EggSizeEnum.ExtraLarge
            ' Process.
        Case Egg.EggSizeEnum.Large
            ' Process.
        Case Else
            Throw New ApplicationException("size is invalid: " & size.ToString)
    End Select
End Sub


下列範例會使用Enum陳述式來定義一組相關的具名常數的值。The following example uses the Enum statement to define a related set of named constant values. 在此情況下,值會是您可能會選擇設計資料庫的資料輸入表單的色彩。In this case, the values are colors you might choose to design data entry forms for a database.

Public Enum InterfaceColors
    MistyRose = &HE1E4FF&
    SlateGray = &H908070&
    DodgerBlue = &HFF901E&
    DeepSkyBlue = &HFFBF00&
    SpringGreen = &H7FFF00&
    ForestGreen = &H228B22&
    Goldenrod = &H20A5DA&
    Firebrick = &H2222B2&
End Enum


下列範例顯示包含正數和負數數字的值。The following example shows values that include both positive and negative numbers.

Enum SecurityLevel
    IllegalEntry = -1
    MinimumSecurity = 0
    MaximumSecurity = 1
End Enum


在下列範例中,As子句來指定datatype的列舉型別。In the following example, an As clause is used to specify the datatype of an enumeration.

Public Enum MyEnum As Byte
End Enum


下列範例示範如何使用的位元列舉。The following example shows how to use a bitwise enumeration. 多個值可以指派給位元的列舉型別的執行個體。Multiple values can be assigned to an instance of a bitwise enumeration. Enum宣告包含FlagsAttribute屬性,表示列舉型別,可以視為一組旗標。The Enum declaration includes the FlagsAttribute attribute, which indicates that the enumeration can be treated as a set of flags.

' Apply the Flags attribute, which allows an instance
' of the enumeration to have multiple values.
<Flags()> Public Enum FilePermissions As Integer
    None = 0
    Create = 1
    Read = 2
    Update = 4
    Delete = 8
End Enum

Public Sub ShowBitwiseEnum()

    ' Declare the non-exclusive enumeration object and
    ' set it to multiple values.
    Dim perm As FilePermissions
    perm = FilePermissions.Read Or FilePermissions.Update

    ' Show the values in the enumeration object.
    ' Output: Read, Update

    ' Show the total integer value of all values
    ' in the enumeration object.
    ' Output: 6

    ' Show whether the enumeration object contains
    ' the specified flag.
    ' Output: True
End Sub


下列範例會逐一列舉型別。The following example iterates through an enumeration. 它會使用GetNames方法來擷取列舉的成員名稱的陣列和GetValues擷取成員值的陣列。It uses the GetNames method to retrieve an array of member names from the enumeration, and GetValues to retrieve an array of member values.

Enum EggSizeEnum
End Enum

Public Sub Iterate()
    Dim names = [Enum].GetNames(GetType(EggSizeEnum))
    For Each name In names
        Console.Write(name & " ")
    ' Output: Jumbo ExtraLarge Large Medium Small 

    Dim values = [Enum].GetValues(GetType(EggSizeEnum))
    For Each value In values
        Console.Write(value & " ")
    ' Output: 0 1 2 3 4 
End Sub

另請參閱See also