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

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

語法Syntax

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

組件Parts

  • 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. 您只能在列舉本身(而不是其任何成員)上指定ShadowsYou 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.

備註Remarks

如果您有一組不變的值是以邏輯方式相互關聯,您可以在列舉中將它們定義在一起。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. 您可以藉由將Imports語句加入至原始程式檔,來避免需要使用完整名稱。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. 您可以指定 ByteIntegerLongSByteShortUIntegerULongUShortYou 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 會將它初始化為零(如果它是中的第 member 一個 memberlist ),或設為大於前面緊接的一個值 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. 不過,您可以使用轉換關鍵字(例如 CByte 和) CShortHowever, you can use conversion keywords such as CByte and CShort. AscW如果您以常數或引數呼叫它,您也可以使用 String Char ,因為它可以在編譯時期進行評估。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.

修飾詞Modifiers

類別、結構、模組和介面成員列舉預設為公用存取。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. 您可以將其存取層級調整為 [公用],而不是 [私人] 或 [受保護]。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. 因此,在宣告 Shared Static 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. 我們也建議 "None" 是值為0的成員名稱。We also recommend that "None" be the name of a member whose value is 0. 如需其他指導方針,請參閱 FlagsAttributeEnumFor additional guidelines, see FlagsAttribute and Enum.

範例Example

下列範例顯示如何使用 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
        Jumbo
        ExtraLarge
        Large
        Medium
        Small
    End Enum

    Public Sub Poach()
        Dim size As EggSizeEnum

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

範例Example

下列範例中的方法是在類別之外 EggThe 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

範例Example

下列範例會使用 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

範例Example

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

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

範例Example

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

Public Enum MyEnum As Byte
    Zero
    One
    Two
End Enum

範例Example

下列範例顯示如何使用位列舉。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.
    Console.WriteLine(perm.ToString)
    ' Output: Read, Update

    ' Show the total integer value of all values
    ' in the enumeration object.
    Console.WriteLine(CInt(perm))
    ' Output: 6

    ' Show whether the enumeration object contains
    ' the specified flag.
    Console.WriteLine(perm.HasFlag(FilePermissions.Update))
    ' Output: True
End Sub

範例Example

下列範例會逐一查看列舉。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
    Jumbo
    ExtraLarge
    Large
    Medium
    Small
End Enum

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

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

另請參閱See also