C # Enum -- Enumeration

Source: Internet
Author: User
Tags constant definition

Enumeration

The enumerated type Declaration defines a type name for a group of related symbol constants. Enumeration is used for "Multiple Choices", that isProgramThe runtime is determined by the fixed number of "Choices" that have been set at the time of compilation.

Enumeration type (also called enumeration) provides an effective method to define a group of named Integer constants that can be assigned to variables. For example, if you must define a variable, the value of this variable indicates one day in a week. This variable can only store seven meaningful values. To define these values, you can use the enumeration type. The enumeration type is declared using the enum keyword.

Enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

By default, the basic type of each element in the enumeration is int. You can use a colon to specify another Integer type.
If you do not specify a value for the element in the list of enumerative numbers, their values will automatically increase in increments of 1. In the previous example, the value of days. Sunday is 0, the value of days. Monday is 1, and so on. When creating a new days object, if you do not explicitly assign a value to it, it will have the default value days. Sunday (0 ). When creating an enumeration, select the most reasonable default value and assign it a zero value. This means that as long as the enumeration is not explicitly assigned a value when it is created, all the enumerated values will have the default value. It must be in lower case or lower case in enumeration, but this is not recommended.

Note: system. the enum type is the abstract base class of all enumeration types (it is a unique type different from the basic type of enumeration), and. the members inherited by Enum are available in any enumeration type. There is a boxing conversion from any enumeration type to system. Enum, And the unboxing conversion from system. Enum to any enumeration type exists.System. Enum is not an enumeration type. Instead, it is a class type and all enumeration types are derived from it. The type system. Enum is derived from the type system. valuetype, and the latter is derived from the type object. At runtime, the value of the system. Enum type can be null or reference to any enumerated type containing the box value.

Advantages of enumeration:
<1> enable EnumerationCodeIt is easier to maintain and helps to specify valid and expected values for variables.

<2> enumeration makes the code clearer. descriptive names are allowed to represent integer values rather than fuzzy numbers.

<3> enumeration makes the code easier to type. When assigning values to enumeration instances, vs. Net ide uses intelliisense to pop up a list box containing acceptable values, which reduces the number of buttons and allows us to recall possible values.

Enumeration instances

Statement:

Public   Enum Timeofday
{
Moning =   0 ,
Afternoon =   1 ,
Evening =   2 ,
};

Usage:

Public   String Gettimeofday (timeofday time)
{
String Result =   String . Empty;
Switch (Time)
{
Case Timeofday. moning:
Result =   " Morning " ;
Break ;
Case Timeofday. Afternoon:
Result =   " Afternoon " ;
Break ;
Case Timeofday. Evening:
Result =   " Evening " ;
Break ;
Default :
Result =   " Unknown " ;
Break ;
}
Return Result;
}

 

Enumeration Method 

<1> retrieve enumerative strings

Timeofday time = Timeofday. afternoon;

Console. writeline (time. tostring ());//Output: afternoon

 

<2> enum. parse () method. This method includes 3 Parameters. The first parameter is the enumeration type to be used. Its syntax is a keyword. Typeof Followed by the enumerated class name in brackets. Typeof The operator is 5 Chapter. The second parameter is the string to be converted, and the third parameter is Bool Specifies whether to ignore the case when converting. Finally, note that Enum. parse () The method actually returns an object reference.-- We need to explicitly convert this string to the desired enumerated type ( This is an example of unboxing. ) . For the above Code 1 , As an object, corresponds Timeofday. Afternoon . Explicitly convert Int Will be generated again 1.

Timeofday time2 = (Timeofday) enum. parse ( Typeof (Timeofday ), " Afternoon " , True );

Console. writeline ((Int) Time2 );//Output 1

 

<3> obtain the name of an enumerated value.

Lbone. Text = Enum. getname ( Typeof (Timeofday ), 0 ); Lbone. Text = (Timeofday) 0 ). Tostring (); // Return: Morning

 

Both methods can be implemented, but when the value is out of bounds (not the value listed in enumeration), there is a certain difference. You can select an appropriate method based on your needs.

Lbcon. Text = (Timeofday) 5 ). Tostring (); // Return Value: 5. If this parameter is exceeded, the original value is returned.

This . Lbgetname. Text = Enum. getname ( Typeof (Timeofday ), 5 ); // Return: Null String. If it is out of the range, an empty string is returned.

 

<4> obtain all enumerated values.

Foreach ( Int I In Enum. getvalues ( Typeof (Timeofday )))
Lbvalues. Text + = I. tostring ();

<5> enumerate all names

Foreach ( String Temp In Enum. getnames ( Typeof (Timeofday )))
Lbnames. Text + = Temp;

Enumeration and constants

Enumeration is preferred.

In C #, the true strength of enumeration is that they will be instantiated in the background as a structure derived from the base class system. enum. This indicates that you can call methods to execute useful tasks. Note that because of the execution method of the. NET Framework, there is no performance loss if you use enumeration as a structure in syntax. In fact, once the code is compiled, enumeration becomes the basic type, similar to int and float.

However, in practical applications, you may find that we often define enumeration types in English, because development tools are originally developed in English and used by Americans, you can directly understand the meaning of the enumeration type. In fact, we did one more step during development and needed to translate enumeration types. No way.Programming LanguageIt is written in English. If it is written in Chinese, we do not need to translate it. It is very convenient to use enumeration. For example, timeofday. when morning sees morning, the Americans know it is morning, but for Chinese users, there may be a lot of people who don't understand it. This requires us to translate and explain it and go up to gettimeofday () the translation is actually done. Therefore, it is not very convenient to use enumeration. Sometimes we prefer to create constants and declare a set in the class to hold constants and their meanings.

Using constant definition: This method is feasible, but it cannot be guaranteed that the input parameter day is actually limited.

Using System;
Using System. Collections. Generic;

Public   Class Timesofday
{
Public   Const   Int Morning =   0 ;
Public   Const   Int Afternoon =   1 ;
Public   Const   Int Evening =   2 ;
Public   Static Dictionary < Int , String > List;
///   <Summary>
/// Obtain the day of the week
///   </Summary>
///   <Param name = "day"> </param>
///   <Returns> </returns>
Public   Static   String Gettimenameofday ( Int Time)
{
If (List =   Null   | List. Count <=   0 )
{
List =   New Dictionary < Int , String > ();
List. Add (morning, " Morning " );
List. Add (afternoon, " Afternoon " );
List. Add (evening, " Evening " );
}

ReturnList [time];
}
}

For questions about Chinese display, click here


code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> Public Enum timeofday
{< br> morning,
afternoon,
evening,
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.