In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "detailed introduction of enumerations in C#". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the detailed introduction of enumerations in C#.
Zero, basic knowledge
An enumeration is a value type declared by the developer that declares a named constant value at compile time. Using enumerations can make our code simple and readable. Let's take a look at two code snippets:
/ / Code snippet 1 void Method (int country) {switch (country) {case 0: / / more code break; case 1: / / more code break; case 2: / / more code break; case 3: / / more code break; default: / / more code break;}} / / Code snippet 2 void Method (Country country) {switch (country) {case Country.CN: / / more code break; case Country.JP: / / more code break; case Country.UK: / / more code break Case Country.USA: / / more code break; default: / / more code break;}}
From the two code snippets above, we can see that there is a clear difference between the two. We have almost no idea what the case value in the first code represents, but in the second code we use enumerations, through which we can immediately know what we are trying to say. Similarly, using enumerated values instead of Boolean values can also improve the readability of the code. For example, if we want to develop a program that turns the console light on and off, the code can be written as LightOperating (True), but we can't see what to do with this code. Now let's change the code to LightOperating (Light.On). After modifying the code, it is easy to see what you are trying to say.
1. There are two ways for enumeration definition and value definition enumeration, which are normal way and custom way. Either way, the keyword enum is required to identify the type as an enumerated type, and enumerated values are implemented as integer constants. Let's take a look at how these two ways define enumerations. The common way is often used by us, and it is also the default way. This approach is simple and the code is as follows:
Enum Country {CN, UK, JP, USA}
In the above code segment, we define a country enumeration. the integer constant for the first enumeration value is 0, the integer constant for the second enumeration value is 1, and the integer constants for the subsequent enumeration values are 2 and 3, respectively. But in some cases we need to customize the integer constant corresponding to the enumerated value, and then we need to use the custom way. The custom method is also known as explicitly assigning an enumerated value, and its method is as follows:
Enum Country {CN = 3, UK, JP = 70, USA = 67}
In the code, we set the integer constant corresponding to the first enumeration value to 3, then the integer constant of the second enumeration value is not 1, but 4, because when the enumeration value does not show the assignment, it will add 1 to the integer value corresponding to the previous enumeration value as its own integer value. The last two enumerated values are explicitly assigned, so the corresponding integer values are the assigned values. Enumerating values is also very simple, just enumerating names. Enumerate values, such as Country.UK.
Tip: here are some suggestions:
The name of the enumerated value should not contain the enumerated name; the enumerated name should appear in the singular (except for attributes).
two。 Types of enumerations so far we have defined the base type int type used by enumeration types, but enumerations can use not only int types, but also all base types except char types. We can use inheritance syntax to specify other types.
Enum Country:short {CN = 3, UK, JP = 70, USA = 67}
In the above code, we explicitly define the base type used by the enumeration to be short. Although inheritance syntax is used here, no inheritance relationship is established. All enumerated base classes are System.Enum. These classes are sealed classes and cannot derive new members from existing enumerated types. For variables of enumerated types, the value is not limited to the value named in the declaration, so the value can be converted to the underlying type, so it can be converted to the enumerated type. The reason for this design is that in future API, it is very possible to add new values to enumerations without breaking the old version. But there is also a drawback: enumerations allow unknown values to be assigned at run time, which we need to take into account when developing. And when you add a new enumeration value to the enumeration later, you should add it to the end of all enumeration values, or display the value corresponding to the specified enumeration value, so as to avoid the numerical change corresponding to the enumeration value in the enumeration type due to the addition of the new value.
Tip: we should try to use int as the base type for enumerations in development, except for performance problems or interoperability considerations.
I. enumeration conversion
Enumeration conversion mainly involves the conversion of enumerations and enumerations, and the conversion of enumerations and numbers and strings.
1. Conversion between enumerations the first thing I want to say is that direct conversion between different enumeration arrays is not supported in C #, so if we want to achieve conversion between different enumeration arrays, we can take advantage of CLR's loose assignment compatibility to convert, the two enumerations that need to be converted must have the same base type. Again, let's take a look at the implementation through an example.
Static void Main (string [] args) {CountryAllName [] can = (CountryAllName []) (Array) new Country [4];} enum Country {CN, UK, JP, USA} enum CountryAllName {China, UnitedKingdom, Japan, UnitedStates}
Unexpected errors or results can occur when using this method, and the relevant development specifications do not say that this approach works every time, so I do not recommend it, except in some extreme scenarios.
two。 Conversion between enumerations and strings you can directly use the ToString () method to convert enumerations to strings. Enumerating the value ToString will directly output the string form of the enumerated value identifier, for example, the result of Country.CN.ToString () is the string CN. Of course, you can also use the Enum.GetNames and Enum.GetName methods to get it. Let me briefly explain the use of these two methods.
The GetNames GetNames method needs to pass in an enumerated type, and the return value is an array of strings. For example, if you need to get the second country of Country, you can write Enum.GetNames (typeof (Country)) [1] in this way, and the return result is UK. The GetName GetName method returns a string that is the string form of the specified enumerated value to be obtained. Similarly, we get the second country, Enum.GetName (typeof (Country), 1), and the value returned is also UK. Converting strings to enumerations is also simple, using a static method Parse of the Enum base class. For example, we can convert JP to enumerated values like this (Country) Enum.Parse (typeof (Country), "JP"). It is important to note that the TryParse method does not appear until. Net 4.0, so if you want to convert a string to an enumeration in version 4. 0 or later, you need to do appropriate error handling to prevent the string from not existing in the enumeration value in the enumeration type.
Tip: string-to-enumeration conversions are not localizable; if they must be localized, they must be messages that are not visible to upper-level users. Therefore, conversions between enumerations and strings should be avoided as much as possible in actual development.
3. Conversion between enumerations and numbers We can use strong conversion from enumerations to numbers, for example, (int) Country.CN returns a result of 0. There are two ways to convert numbers to enumerations, one is to use strong conversion, and the other is to use Enum's static square to send ToObject.
The Country country = (Country) 2 ToObject ToObject method needs to pass the enumeration type and the number to be converted, such as Country country = (Country) Enum.ToObject (typeof (Country), 2).
4. Note that both the conversion of strings to enumerations and the conversion of numbers to enumerations must first determine whether the values to be converted are included in the enumerations, and the judgment method is very simple. You only need to call the static method IsDefined of Enum. For example, I want to convert 0 and HK to enumerations. The code is as follows:
Type type = typeof (Country); if (Enum.IsDefined (type,0)) {Enum.ToObject (type,0);} if (Enum.IsDefined (type, "HK")) {Enum.Parse (typeof (Country), "HK");}
Only 0 in the above code is successfully converted to the enumerated value CN, because the enumerated value corresponding to 0 is CN, and HK is not in the enumeration.
III. Signs and attributes
In this section, we'll talk about flags and attributes, which are rarely used in development, and most programmers don't know much about them.
1. Flags in development, sometimes we want to be able to combine enumerations to represent compound values, then we need to define flag enumerations, the name of flag enumerations is plural, representing a collection of flags. Generally, we use bitwise or operator chained enumerated values, and use the HasFlags method or bitwise and operator to determine whether a particular bit exists. A more classic flag enumeration is the FileAttributes flag enumeration in the System.IO namespace, which lists all the attributes of the file, such as read-only, hidden, disk, and so on, and all the enumeration values it contains can be combined with each other, for example, a file is both a hidden file and a read-only file. The methods to define flag enumerations are as follows:
[Flags] enum WeekDays {Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16, Saturday = 32, Sunday = 64}
You will find a rule in the above code that the integer value corresponding to each enumerated value is to the n power of 2, which is why. In the flag enumeration, the result of the combination of multiple enumeration values can not be included in the flag enumeration, and based on the characteristics of bitwise operation, it is convenient to use the bit operator to calculate whether one enumeration value contains another enumeration value. this is quite useful in permission systems.
two。 Properties can also be used on property enumeration values. For example, if we need to print the Chinese name of the output enumeration value, we can set it in the form of properties. First, we need to define a property:
Public class EnumChineseAttribute: Attribute {private string get; public EnumChineseAttribute (string chineseName) {m_strDescription = chineseName;} public string Description {get {[EnumChinese ("China")] CN, [EnumChinese ("UK")] UK, [EnumChinese ("Japan")] JP, [EnumChinese ("USA")] USA} static void Main (string [] args) {Country country = Country.CN; FieldInfo fieldInfo = country.GetType (). GetField ("CN") Object [] attribArray = fieldInfo.GetCustomAttributes (false); EnumChineseAttribute attrib = (EnumChineseAttribute) attribArray [0]; Console.WriteLine (attrib.Description); Console.Read ();}
Through the above code, we can get the corresponding Chinese name of CN. This code has not been further optimized and must be encapsulated and optimized in the actual project.
At this point, I believe you have a deeper understanding of the "detailed introduction of enumerations in C#". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.