This article mainly summarizes the application of C # enumeration in my actual project. If there are any deficiencies, you are welcome to point out.
I. Basic Application of enumeration
1. enumeration can be understood as a constant combination or a type. For example, the following enumeration definition:
public enum MicrosoftTechnology
{
CSharp,
ASPNETMVC,
SQLServer,
WCF,
SilverLight,
}
The default enumeration value is int type. You can specify the enumerated data type as needed. For example, public enum MicrosoftTechnology: long. The int values of the MicrosoftTechnology enumeration are
Csharp: 0; ASPNETMVC: 1; SQLServer: 2; WCF: 3; SilverLight: 4, automatically assigned values in the form of auto-increment 1. You can also specify the value of each enumeration item.
2. bitwise operation of enumeration:
The Flag feature indicates that enumeration supports bitwise operations. Generally, we use the following bitwise operators: & (and), | (OR), and ),~ (Not ).
After we add the [Flags] feature to the enumerationSpecify the enumerated Value.
Set1,The code in is modified as follows:
[Flags]
public enum MicrosoftTechnology
{
CSharp = 1,
ASPNETMVC = 2,
SQLServer = 4,
WCF = 8,
SilverLight = 16,
}
Here, the enumerated values are mainly used for the use of the and, Or, non-three bitwise operators. Convert enumerated values to binary values:
CSharp: 1 = 0001
ASP netmvc: 2 = 0010
SQLServer: 4 = 0100
WCF: 8 = 1000
SilverLight = 16 = 10000
Example:
If a developer chooses two Microsoft technologies: CSharp and ASPNETMVC, the bits can be 0001 | 0010 = 0011. After unremitting efforts, the developer mastered the above two technologies "0011 ". Now we want to use bitwise operations to check whether the developer is proficient in CSharp: the code is:
(MicrosoftTechnology. CSharp | MicrosoftTechnology. ASPNETMVC) & MicrosoftTechnology. CSharp equals (0001 | 0010 = 0011) & 0001 equals 0001 (CSharp: 1)
At this point, I think it is not difficult to understand: In order to specify the enumerated value when applying bits to enumeration. Non (~) The operator is left to the reader for practice.
2. Perform localization for enumeration
Compile the general method of enumeration localization through the. net generic mechanism. The Code is as follows:
1 /// <summary>
2 // general method of local Enumeration
3 /// </summary>
4 /// <returns> </returns>
5 /// <author> Ryanding </author>
6 private static string LocalizeEnumeration (object enumerator)
7 {
8
9 ResourceManager resources = new ResourceManager ("resx file name ",
10 System. Reflection. Assembly. GetExecutingAssembly ());
11
12 string name = String. Format ("{0}. {1}. Text", enumerator. GetType (). Name, enumerator );
13 string localizedDescription = resources. GetString (name );
14
15