enum--enumeration for C #

Source: Internet
Author: User
Tags constant definition

Enumeration

An enumeration type declaration defines a type name for a set of related symbolic constants. Enumeration is used for "multiple selection" scenarios where the program runs from a fixed number of "choices" that have been set at compile time.

An enumeration type (also known as an enumeration) provides an efficient way to define a set of named integer constants that can be assigned to variables. For example, suppose you must define a variable with a value that represents the day of the week. This variable can store only seven meaningful values. To define these values, you can use an enumeration type. Enumeration types are declared using the enum keyword.

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


By default, the underlying type of each element in the enumeration is int. You can use a colon to specify another integer value type.
If you do not specify values for the elements in the enumeration list, their values are automatically incremented in increments of 1. In the previous example, the value of Days.sunday is 0,days.monday with a value of 1, and so on. When you create a new days object, it will have a default value of Days.sunday (0) If you do not explicitly assign it a value. When you create an enumeration, you should choose the most reasonable default value and assign it a value of 0. This makes it possible for all enumerations that are created to have that default value as long as they are not explicitly assigned when the enumeration is created. Enumeration is case sensitive, but it is not recommended.

Note: The System.Enum type is the abstract base class for all enum types (it is a unique type that differs from the underlying type of the enumeration type), and the members inherited from System.Enum are available in any enum type. There are boxing conversions from any enumerated type to System.Enum, and there is an unboxing conversion from System.Enum to any enumerated type. System.Enum itself is not an enumeration type. Instead, it is a class type, and all enum types are derived from it. The type System.Enum derives from the type System.ValueType and the latter derives from the type object. At run time, the value of type System.Enum can be null or a reference to the bin value of any enumerated type.

Advantages of the enumeration:
1. Enumerations can make code easier to maintain, helping to ensure that the variable is given a valid, expected value.
2. Enumerations make the code clearer, allowing the representation of an integer value with a descriptive name instead of a fuzzy number.
3. Enumerations make code easier to type. When assigning a value to an instance of an enumeration type, the Vs.net ide pops up a list box with an acceptable value through IntelliSense, reducing the number of keystrokes and allowing us to recall possible values

Enumerating Instances

Statement:

public enum TimeOfDay
{
moning = 0,
Afternoon = 1,
Evening = 2,
};

Use:

public string Gettimeofday (TimeOfDay time)
{
string result = String. Empty;
Switch (time)
{
Case timeofday.moning:
result = "Morning";
Break
Case Timeofday.afternoon:
result = "PM";
Break
Case timeofday.evening:
result = "Night";
Break
Default
result = "Unknown";
Break
}
return result;
}

Enumeration Methods

1. Get the enumeration string

TimeOfDay time = Timeofday.afternoon;

Console.WriteLine (Time. ToString ());//output: Afternoon

2, Enum.parse () method. This method takes 3 parameters, and the first parameter is the enumeration type to use. The syntax is the keyword typeof followed by the enumeration class name, enclosed in parentheses. The typeof operator is discussed in detail in Chapter 5. The second argument is the string to be converted, and the third argument is a bool that specifies whether the case is ignored when the conversion occurs. Finally, note that the Enum.parse () method actually returns an object reference--we need to explicitly convert the string to the desired enumeration type (This is an example of an unboxing operation ). For the above code, 1 is returned as an object that corresponds to the enumeration value of Timeofday.afternoon. When you explicitly convert to an int, 1 is generated again .

TimeOfDay time2 = (TimeOfDay) enum.parse (typeof (TimeOfDay), "Afternoon", true);

Console.WriteLine ((int) time2);//Output 1

3. Get the name of a value that is enumerated

Lbone.text = Enum.getname (typeof (TimeOfDay), 0); Lbone.text = ((TimeOfDay) 0). ToString ();//return: Morning

Both methods can be implemented, but when their values are out of bounds (not the values listed in the enumeration), there is a certain difference. You can choose the right method according to your own needs.

Lbcon.text = ((TimeOfDay) 5). ToString (); Returns: 5 If the original value is returned out of bounds

This.lbGetName.Text = Enum.getname (typeof (TimeOfDay), 5); Returns an empty string if an empty string is returned out of bounds

4. Get all the values of the enumeration

foreach (int i in Enum.getvalues (typeof (TimeOfDay)))
Lbvalues.text + = i.ToString ();

5. Enumerate all the names

foreach (String temp in Enum.getnames (typeof (TimeOfDay)))
Lbnames.text+=temp;

Enumerations and Constants

Precedence is given to enumerations.

In C #, the real power of enumerations is that they are instantiated in the background as a struct that derives from the base class System.Enum. This means that you can invoke methods on them and perform useful tasks. Note that because of the way the. NET framework is executed, there is no performance penalty for the syntax of enumerating enumerations as structs. In fact, once the code is compiled, the enumeration becomes the base type, similar to int and float.

But in practical applications, you might find that we often define enumeration types in English, because development tools are developed in English, and Americans use them to understand the meaning of enumerated types directly. In fact, we have one more step in the development, we need to translate the enumeration type. No way, who let the programming language is written in English, if it is written in Chinese, then we do not have to translate, with the enumeration became very convenient. To give a simple example, timeofday.morning see morning, Americans know is the morning, but for Chinese users, there may be many people can not understand, which requires us to translate, explain, to the above the Gettimeofday () method, is actually doing translation work. Therefore, when using enumerations, it is not very convenient to feel, sometimes we are more willing to create constants, and then in the class, declare a collection to accommodate the constant and its meaning.

Use constant definition: This method is feasible, but there is no guarantee that the passed parameter day is actually qualified.

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>
Get 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, "PM");
List. ADD (Evening, "Night");
}

return List[time];
}
}

enum--enumeration for C #

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.