Usage of enumerated types

xiaoxiao2021-03-06  86

C # language specification

14.3 enumeration member

The enumeration type declared body is used to define a zero or multiple enumeration members, which are the name constants of the enumeration type. Any two enumeration members cannot have the same name.

Enum-member-declarations: (enumeration member statement :)

Enum-member-declaration (enumeration member statement)

ENUM-Member-Declarations,

Enum-member-declaration (enumeration member statement, enumeration member statement)

Enum-member-declaration: (enumeration member statement :)

AttributeSopt Identifier

Optional identifier)

AttributeSopt Identifier =

Constant-expness

Optional identifier = constant expression)

Each enumeration member has associated constant values. The type of this value is the basic type of the enumeration of it. The constant value of each enumeration member must be within the range of the basic type of the enumeration. Example

ENUM color: uint

{

RED = -1,

Green = -2,

Blue = -3

}

Generating compile time errors because constant value -1, -2 and -3 are not within the range of the foundation integer UINT.

Multiple enumeration members can share the same association value. Example

ENUM Color

{

RED,

Green,

Blue,

Max = blue

}

Display an enumeration, two enumerated members (Blue and Max) have the same association value.

An enumeration value or implicitly assigned value or explicitly assigned. If the enumeration member has a "constant expression" initial value setting item, the value of the constant expression (it implicitly converted to enumeration) is the association value of the enumeration member. If the declaration of the enumeration member does not have an initial value setting item, its association value is implicitly set by the following rules:

If the enumeration member is the first enumeration member declared in the enumerated type, its association value is zero. Otherwise, the association value of the enumeration member is obtained by adding the previous enumeration member (in the text order). This increased value must be within the range of the value of the fundamental type; otherwise, the compile time error occurs.

Example

Using system;

ENUM Color

{

RED,

Green = 10,

Blue

}

Class test

{

Static void main () {

Console.writeline (StringFromColor);

Console.writeline (StringFromColor);

Console.writeline (StringFromColor);

}

STATIC STRING STRINGFROMCOLOR (Color C) {

Switch (c) {

Case color.red:

Return string.format ("RED = {0}", (int) c);

Case Color.green:

Return string.format ("Green = {0}", (int) c);

Case color.blue:

Return string.Format ("Blue = {0}", (int) c);

DEFAULT:

Return "Invalid Color";

}

}

}

Output enumeration member name and their association value. The output is: RED = 0

Green = 10

Blue = 11

The reason is as follows:

Enumeration member Red is automatically configured (because it does not have an initial value setting item and is the first enumeration member). Enumeration member Green is explicitly assigned a value 10. The enumeration member Blue is automatically given the value of the member of the member 1 in front of it.

The associated value of enumeration members cannot use its own value to use its own associated enumeration member directly or indirectly. In addition to this loopability limit, the enumeration member initial value setting item can freely reference other enumeration member initial value setting items without having to consider the order of the text positions thereof. In the enumeration member initial value setting item, the value of other enumeration members is always considered to belong to the corresponding basic type, so there is no need to use forced conversion when referenced by other enumeration members.

Example

ENUM CIRCULAR

{

A = B,

B

}

Generate compilation errors because A and B declarations are looped. A Explicitly dependent on B, and B is implicitly dependent on A.

Enumeration members' naming methods and scopes are fully similar to the fields in the class. The scope of enumeration member is a body that contains its enumeration type. Within this range, enumeration members can be referenced by their simple names. In all other code, the name of the enumeration member must be limited by the name of its enumeration type. Enumeration members do not have any declarative accessibility, if an enumeration type is accessible, all enumeration members it contain are accessible.

Send Microsoft Feedback on this topic

© Microsoft Corporation. all rights reserved.

Let's first look at this NUnit test code, we want to use the reflex mechanism to access an object's enumeration type domain or property:

[TestFixture] public class PaymentInfo {public enum PaymentType {Cash, CreditCard, Check} public PaymentType Type; public void Test () {PaymentInfo payment = new PaymentInfo (); payment.Type = PaymentType.Cash; System.Reflection.FieldInfo enumField = . GetType () GetField ( "Type"); int paymentTypeInt32; paymentTypeInt32 = (int) enumField.GetValue (payment); Assert.AreEqual ((int) PaymentType.Cash, paymentTypeInt32); enumField.SetValue (payment, paymentTypeInt32); Assert .Arequal (paymenttype.cash, payment.type);}}

It is found that an exception is thrown when the test is running at this line: "The object type cannot be converted to the target type." The reason is that it is because the reflection mechanism of the CLR does not allow implicit conversion between the enumeration type and integer type. However, the C # compiler or allows us to perform explicit conversions between the two through the syntax of the mandatory type.

In this test, it is actually very simple in this test: the scribe portion is forced to convert to an enumeration type, such as: (paymenttype) PaymentTypeInt32. The problem is: How do you dynamically convert the type during runtime? For example, when I am writing Elegantdal, I need to write a type of type INT from the database to INT to an enumeration field of the object you want to return. At this time, I only have FieldInfo, ColumnValue and ResultObject, but write into FieldInfo. .SetValue (ResultObject, ColumnValue) will appear the previously mentioned error, but I only have a running type information (FieldInfo.fieldType), I can't write into FieldInfo.SetValue (ResultObject, (FieldInfo.fieldType) ColumnValue ... ...

I have to list this as a special case, and our salvage is an enum.TOOBJECT () method - Do you know if there is a better way to solve this problem? Enumeration Type is another lightweight value type in C #, C # uses a set of specific values ​​to express a set of specific values, such as Windows Forms, and the style of the button control. The following pseudo-code shows a typical application enumeration usage: public enum WritingStyle {Classical, Modern, Elegant,} class Essay {public void Write (WritingStyle writingStyle) {switch (writingStyle) {case WritingStyle.Classical: // Writing Classical Break; Case Writingstyle.modern: // Modern Writing Style Break; Case Writingstyle.egant: // Elegant Writing Style Break; Default: Throw (New System.ArgumentException ("Invalid Writing Style");}}} Note The above enumeration symbol Classical, Modern, Elegant is separated by a comma "," rather than the semicolon ";" The last enumeration value Elegant can be saved. Like the structure, the enumeration in C # does not allow it to have its own inheritance of the parent class system.enum, the same, enumeration can't be inherited, no Abstract. The System.enum class provides a lot of easy-to-use features for enumeration types. For example, we can get the string symbolic representation of our declaration values ​​via the getName method. The following example shows some of the more common operations: using System; public enum WritingStyle {Classical, Modern, Elegant,} class Test {public static void Main () {WritingStyle dw = WritingStyle.Modern; Console.WriteLine (Enum.GetName ( TypeOf (WritingStyle), DW); console.writeline (dw.tostring ()); console.writeline (enum.getunderlyingType (TypeOf (Writingstyle)));}} The last line outputs System.Int32, how is this? What's going on? We know that int is a short written form of System.Int32. Is our WritingStyle enumeration type and integer int type? Yes, the enumeration and integer values ​​of C # are strictly distinguished, for example, we cannot be assigned to DW = 1 in the above code. However, each enumeration value does have a value of an integer type, and can be converted, but this conversion must be expressed in a clear transformation syntax.

转载请注明原文地址:https://www.9cbs.com/read-107157.html

New Post(0)