1. Before learning enumeration, first listen to the advantages of enumeration.
1. Enumeration can make the code clearer, and it allows descriptive names to represent integer values.
2. Enumeration makes the code easier to maintain and helps ensure that the variable is specified with legal, expected values.
3. Enumeration makes the code easier to enter.
2. Enumeration description
1. Simple enumeration
(1) Enum is declared using the enum keyword, which is the same as the class.Enumerations themselves can have modifiers, but the members of the enum are always public and cannot have access modifiers. The modifiers of the enum itself can only use public and internal。
(2) Enumeration is a value type, implicitly inherited from, and cannot be modified manually. It is a reference type itself, inherited from.
(3) Enumerations are implicitly sealed and are not allowed to be derived from subclasses as base classes.
(4) The enumeration members of the enumeration type are all static and default to the Int32 type.
(5) Each enumeration member has an associated constant value. The type of this value is the underlying data type of the enum. The constant value of each enum member must be within the scope of the underlying data type of the enum. If the underlying data type is not specified explicitly, the default data type is int type.
(6) The enum members cannot be the same, but the values of the enum can be the same.
(7) Enumerate the comma and the semicolon after the braces of the last member can be omitted
C# provides a class to facilitate the operation of enumeration. The following is a common method for this class:
method | name |
CompareTo | Compare this instance with the specified object and return an indication of the relative values of both |
Equals | Indicates whether this instance is equal to the specified object |
Format | Convert the specified value of the specified enumeration type to its equivalent string representation according to the specified format |
GetName | Search the name of a constant with the specified value in the specified enum |
GetNames | Retrieve an array of constant names in the specified enum |
GetTypeCode | Return the basis of this instance TypeCode |
GetUnderlyingType | Returns the basic type of the specified enum |
GetValues | Search for an array of constant values in an enum |
HasFlag | Determines whether one or more bit fields are set in the current instance |
IsDefined | Returns an indication of whether there is a constant with the specified value in the specified enum |
Parse | Converts a string representation of one or more enumeration constants' names or numeric values into an equivalent enumeration object. A parameter specifies whether the operation is case-insensitive |
TryParse | Converts a string representation of one or more enumeration constants' names or numeric values into an equivalent enumeration object. Return value to indicate whether the conversion is successful |
It is simple to display the underlying data type of the specified enum. Just add a colon when declaring the enum, followed by the data type to be specified.
enum sex : byte//Show the underlying data type of the specified enum { male, female,//This comma can be omitted }; //This semicolon can be omitted
Explicitly set the enum member constant value, which starts from 0 and increments one by one by one. However, the following example is set to 1, 2, 3, 4, 5, 6, 7, 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 cannot } ((int));//Get the value
Example, get the enum name from the enum value and get the enum value from the enum name
class Program { static void Main(string[] args) { ((typeof(Man),1)); //Or Liu Bei (get the name from the value) string[] array1 = (typeof(Man)); (array1[1]); //Guan Yu Array array2 = (typeof(Man)); ((1)); //It's still Guan Yu Type t = (typeof(Man)); (t); //Output Int32 //Get content from value int i = 1; string Name = (typeof(Man), ()).ToString(); //At this time Name="Liu Bei" (Name); //Get content from value string Name2 = "Guan Yu"; int j = Convert.ToInt32((typeof(Man), Name2)); //At this time j=2 (j); (); } } enum Man { Liu Bei = 1, Guan Yu = 2, Zhang Fei = 3 }
2. Sign enumeration
The flag enumeration must be declared with the [] feature on the top. And enumeration supports combination operations. Let's take a look at an example first
class Program { static void Main(string[] args) { var man = Week.white | Week.beautiful; //The value is 101. Calculate method 001 or 100 on it, and the result is 101. ((int)man); if ((man & Week.white) == Week.white) //101 man { //001 White, each bit is in harmony, ("This person is white"); //001 If the result is white, you can reversely introduce man including white } else { ("This person is black"); } (); } } [] public enum Week { white = 1, //001 rich = 2, //010 beautiful = 4, //100 }
This kind of bit operation is very useful and also supports bit operation in SQL statements. In other words, after saving the result of an enumeration operation into the database, it can still be read according to your requirements. for example:
If a "white beauty" value is stored as a database, then the integer 5 is stored.
So how do I read out all the "white" data lists? White can be pure white "1", white rich 3, white beautiful 5, or white rich 7, you can read it with in, but a better way is to use bit operations in the SQL statement.
select * from Table1 where Tag & 1 = 1//Tag is the column name select * from Table1 where Tag | 1 = Tag
3. Suggestions for using enumeration
When enumerations can be made in parameters, return values, variables, etc., try to use enumerations (be careful to consider the stability of the classification)
In most cases, int type enumeration can be used, except for the following cases.
Enumerations may be used frequently, and in order to save space, enumerations smaller than int type can be used.
Enumeration of flags, and there are more than 32 flags.
Here is an example of enumeration binding MVC3 drop-down list:
Controller code:
namespace { public class HomeController : Controller { public ActionResult GetSexList() { Dictionary<string, int> Sexlist = new Dictionary<string, int>(); string[] keys = (typeof(sex)); Array values = (typeof(sex)); for (int i = 0; i < ; i++) { (keys[i], (int)(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="@">@</option> } </select>
Generated HTML code:
<select> <option value="1">male</option> <option value="2">female</option> <option value="3">other</option> </select>
Let's take another example to get the enum description
public static class GetDescription { /// <summary> /// Get description information /// </summary> /// <param name="en"></param> /// <returns></returns> public static string description(this Enum en) { Type type = (); MemberInfo[] memInfo = (()); if (memInfo != null && > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(), false); if (attrs != null && > 0) return ((DescriptionAttribute)attrs[0]).Description; } return (); } } public enum Sex { [Description("male")] man = 1, [Description("female")] woman = 2, [Description("other")] other = 3 }
The above is the detailed content of quickly learning c# enumeration. For more information about c# enumeration, please follow my other related articles!