C # Enumeration

Source: Internet
Author: User
Original article: C # Enumeration

1. Before learning enumeration, first listen to the advantages of enumeration.

1. Enumeration makes the code clearer. It allows descriptive names to represent integer values.

2. Enumeration makes the code easier to maintain and helps to specify valid and expected values for the variable.

3. Enumeration makes code input easier.

Ii. Enumeration description

  1. simple enumeration

  • Enumeration is declared using the enum keyword, which is the same as the class. Enumeration can have modifiers, but enumeration members are always public and cannot have access modifiers. Only public and internal modifiers can be used for enumeration.
  • Enumeration is a value type that is implicitly inherited from system. Enum and cannot be modified manually. System. Enum is a reference type and inherits from system. valuetype.
  • Enumeration is implicitly sealed and cannot be used as a derived subclass of the base class.
  • All enumeration members of the enumeration type are static, and the default value is int32.
  • Each enumerated member has an associated constant value. The value type is the underlying data type of enumeration. The constant value of each enumeration member must be within the range of the underlying data type of the enumeration. If the underlying data type is not explicitly specified, the default data type is int.
  • The enumerated members cannot be the same, but the enumerated values can be the same.
  • The comma (,) next to the braces (,) of the last member can be omitted.

C # provides a class to facilitate enumeration operations. The following describes common methods for this class:

Method Name
Compareto Compares the instance with a specified object and returns an indication of the relative values of the two.
Equals Indicates whether the instance is equal to the specified object.
Format Converts a specified value of the specified enumeration type to its equivalent string representation based on the specified format.
Getname Retrieve the name of a constant with the specified value in the specified enumeration.
Getnames Retrieves an array of constant names in a specified enumeration.
Gettypecode Returns the basic typecode of this instance.
Getunderlyingtype Returns the base type of the specified enumeration.
Getvalues Specify the array of common values in the enumeration
Hasflag Determines whether one or more single-digit domains are set in the current instance.
Isdefined Returns an indication of whether a constant with a specified value exists in the specified enumeration.
Parse Converts the string representation of one or more enumerated constant names or numeric values to an equivalent enumerated object. Specifies whether the operation is case insensitive.
Tryparse Converts the string representation of one or more enumerated constant names or numeric values to an equivalent enumerated object. Indicates whether the conversion is successful.

 

To display the underlying data type of the specified enumeration, you only need to add a colon when declaring the enumeration, followed by the data type to be specified.

Enum sex: byte // display the underlying data type of the specified enumeration {male, female, // This comma can be omitted}; // This semicolon can be omitted

Explicitly set the constant value of the enumerated members. The default value is from 0 and increments one by one. However, the following example is set to 1, 2, 3, 4, 5, 6, 7, and 0. And the Member values can be the same.

Enum week {Monday = 1, Tuesday = 2, Wednesday = 3, Sunday = 0, everyday = 1 // The value of the member can be set to the same, but the member does not work} console. writeline (INT) Week. monday); // get the value

For example, retrieve the enumerated name from the enumerated value and the enumerated value from the enumerated name.

Class program {static void main (string [] ARGs) {console. writeline (enum. getname (typeof (man), 1); // or Liu Bei (obtained by the value) string [] array1 = enum. getnames (typeof (man); console. writeline (array1 [1]); // Guan Yu array array2 = enum. getvalues (typeof (man); console. writeline (array2.getvalue (1); // or Guan Yu type T = enum. getunderlyingtype (typeof (man); console. writeline (t); // output int32 // int I = 1 from the value; string name = enum. parse (typeof (man), I. tostring ()). tostring (); // name = "Liu Bei" console. writeline (name); // string name2 = "Guan Yu"; Int J = convert. toint32 (enum. parse (typeof (man), name2); // J = 2 console. writeline (j); console. readkey () ;}} Enum man {Liu Bei = 1, Guan Yu = 2, Zhang Fei = 3}

 

  2. Flag Enumeration

To declare the flag enumeration, add the [system. Flags] feature on the top. In addition, enumeration supports combined operations. Let's look at an example.

Class program {static void main (string [] ARGs) {var man = Week. white | Week. US dollars; // value: 101 calculation method 001 or above 100, the result is 101 console. writeline (INT) MAN); If (Man & Week. white) = Week. whitelist) // 101 man {// 001 whitelist phase by phase and, console. writeline (""); // 001 if the result is white, man inclusion White can be reversed} else {console. writeline ("This person is black");} console. readkey () ;}} [system. flags] public Enum week {White = 1, // 001 rich = 2, // 010 US = 4, // 100}

This bitwise operation is very useful and supports bitwise operations in SQL statements. That is to say, after saving the result of an enumeration operation to the database, it can be read according to your requirements. For example:

Store the value of a "white beauty" such as the database value into the database, then the stored value is an integer of 5.

So how can I read all the "white" Data lists? White, it can be pure white "1", it can also be white rich 3, it can be white beautiful 5, it can also be white rich beautiful 7, you can use in to read, however, a better method is to use bitwise operations in SQL statements.

Select * From Table1 where tag & 1 = 1 // tag is the column name select * From Table1 where tag | 1 = tag

 

Iii. Enumeration suggestions

When enumeration can be made for parameters, return values, variables, and other types, use enumeration whenever possible (pay attention to the stability of classification)

Int type enumeration can be used in most cases, except in the following cases.

Enumeration may be frequently used. In this case, enumeration smaller than int type can be used to save space.

Flag enumeration, and more than 32 flag.

Below is an example of enumerative binding to the mvc3 drop-down list:

Controller code:

namespace MvcStart.Controllers{    public class HomeController : Controller    {        public ActionResult GetSexList()        {            Dictionary<string, int> Sexlist = new Dictionary<string, int>();            string[] keys = Enum.GetNames(typeof(sex));            Array values = Enum.GetValues(typeof(sex));            for (int i = 0; i < keys.Length; i++)            {                Sexlist.Add(keys[i], (int)values.GetValue(i));            }            return View(Sexlist);        }    }    public enum sex    {         male = 1,        female = 2,        other = 3    }}

View code:

@model Dictionary<string, int><select>    @foreach(var item in @Model)    {        <option value="@item.Value">@item.Key</option>    }</select>

Generated HTML code:

<select>        <option value="1">male</option>        <option value="2">female</option>        <option value="3">other</option></select>

Let's use another example to obtain the enumeration description.

Public static class getdescription {// <summary> // obtain the description information /// </Summary> /// <Param name = "en"> </param>/ // <returns> </returns> Public static string description (this Enum en) {type = en. getType (); memberinfo [] meminfo = type. getmember (en. tostring (); If (meminfo! = NULL & meminfo. length> 0) {object [] attrs = meminfo [0]. getcustomattributes (typeof (system. componentmodel. descriptionattribute), false); If (attrs! = NULL & attrs. length> 0) Return (descriptionattribute) attrs [0]). description;} return en. tostring () ;}} public Enum sex {[description ("male")] MAN = 1, [description ("female")] Woman = 2, [description ("other")] Other = 3}

 

Related Article

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.