Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of C # enumeration assignment

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the method of C # enumeration assignment". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "what is the method of C # enumeration assignment"?

Q: I noticed that in Code # 02

Field public static literal Aligment Center = int32 (0x00000001)

This statement is obviously an integer assignment, does this mean that the C # enumeration type is essentially an integer type?

A: this shows that enumerated types do have a certain relationship with integer types. In fact, every enumerated type has a corresponding integer type, which we call the underlying type (underlying type), which is used by default, and .NET uses System.Int32. Of course, you can manually specify it as another integer type:

/ / Code # 09 public enum Alignment: byte {Left, Center, Right}

Note that only the integer types listed below can be specified as the underlying types of enumerations: byte, sbyte, short, ushort, int, uint, long, ulong.

Q: why do we need to specify the underlying type of the enumerated type?

A: you can make it accept the default underlying type. Notice Code # 08. You can't find the word "Center" at all, but it exists in C # code. Why? This is because when the code is compiled, the compiler converts the enumerated type to the corresponding numeric value of the underlying type. Instead of pushing "Center" onto the stack, Code # 08 actually pushes the number 1 of type System.Int32 onto the stack. In fact, the underlying types show how to allocate space for enumerated types, and different underlying types take up different resources, which you may need to pay attention to when you are developing on a restricted system.

Assignment of C # enumeration

Q: how are the values of enumerated members specified?

A: if you don't specify the value of the member manually, from the top down, the value of each member is: 0, 1, 2,. In other words, it is a non-negative integer arithmetic sequence with an initial value of 0 and a step size of 1. For example:

/ / Code # 10 public enum Alignment {Left, / / 0 Center, / / 1 Right / / 2}

Q: what if I manually specify the values of some members?

A: then the value of the assigned member is the value you specified. Of course, whether you specify the value of the enumeration member manually or not, the increment step will not change, always 1. To test whether you understand, please state the values of the following enumerated members and the reasons for your judgment (please use the human brain instead of the computer to run the following code):

/ / Code # 11 public enum DriveType: sbyte {CDRom, Fixed =-2, Network, NoRootDirectory =-1, Ram, Removable = Network * NoRootDirectory, Unknown}

Q: how do we get the value of an enumerated member, whether or not the member is manually assigned?

A: you can use System.Enum

Public static Array GetValues (Type enumType)

This method returns an array containing all enumerated members:

/ / Code # 12 / / See Code # 01 for Alignment. Public static void Main () {Alignment [] alignments = (Alignment []) Enum.GetValues (typeof (Alignment)); Console.WriteLine ("Wanna see the values of Alignment's menbers?"); foreach (Alignment ain alignments) Console.WriteLine ("{0Alignment G} = {0Alignment D}", a);} / / Output: / / Wanna see the values of Alignment's menbers? / / Left = 0 / / Center = 1 / / Right = 2

Q: what if I only need the values of some of the enumerated members?

A: then you can convert the enumeration to the IConvertible interface, and then call the corresponding method:

/ / Code # 12 / / See Code # 01 for Alignment. Public static void Main () {IConvertible ic = (IConvertible) Alignment.Center; int I = ic.ToInt32 (null); Console.WriteLine ("The value of Alignment.Center is {0}.", I);} / / Output: / / The value of Alignment.Center is 1.

Q: why do you need to specify the values of enumeration members manually?

A: in general, using the default assignment rule is sufficient, but in some cases, it may make more sense to assign an enumerated member a value that matches the actual situation (model), depending on the model you build.

Let's take a practical example:

/ / Code # 13 public enum CustomerKind {Normal = 90, Vip = 80, SuperVip = 70, InActive = 100} public class Customer {public readonly CustomerKind Kind; private double payment; public double Payment {return m_Payment * (int) Kind / 100;} / / Code here}

I assign a specific value to each member of the enumeration CustomerKind, which is actually a percentage of the customer's discount on shopping. In the Customer class, the Payment property is strongly typed to obtain the value of the enumerated member (that is, the shopping discount rate) and used for payment calculation. As you can see here, the value of an enumerated member can also be obtained through strong type conversion.

Q: since enumerated types can be cast to integers, can integers also be cast to enumerated types?

A: the answer is yes.

/ / Code # 14 / / See Code # 01 for Alignment. Alignment a = (Alignment) 1

But this mechanism may cause you some trouble:

/ / Code # 15 / / See Code # 01 for Alignment. Class Program {static void Main () {Foo ((Alignment) 12345);} static void Foo (Alignment a) {/ / Code here}}

You can't avoid such a prank!

Q: so is there any way to deal with these pranksters?

A:Sure! We can't assume that everyone is so well-behaved, so we need System.Enum.

Public static bool IsDefined (Type enumType, object value)

Now let's improve the Foo method of Code # 15:

/ / Code # 16 / / See Code # 01 for Alignment. Static void Foo (Alignment a) {if (! Enum.IsDefined (typeof (Alignment), a)) throw new ArgumentException ("DO NOT MAKE MISCHIEF!"); / / Code here}

In this way, the prankster will receive a warning (abnormal message). Of course, we don't rule out that some people cause such "pranks" because of carelessness, then the IsDefined method can also help you deal with these situations.

Q: I think we can also use conditional judgment statements to deal with this situation:

/ / Code # 17 / / See Code # 01 for Alignment. Static void Foo (Alignment a) {if (a! = Alignment.Left & & a! = Alignment.Center & & a! = Alignment.Right) throw new ArgumentException ("DO NOT MAKE MISCHIEF!"); / / Code here}

Or

/ / Code # 18 / / See Code # 01 for Alignment. Static void Foo (Alignment a) {switch (a) {case Alignment.Left: Console.WriteLine ("Cool~"); break; case Alignment.Center: Console.WriteLine ("Well~"); break; case Alignment.Right: Console.WriteLine ("Good~"); break Default: Console.WriteLine ("DO NOT MAKE MISCHIEF!"); break;}}

A: you can definitely do that! In fact, if you are in one of the following situations:

1. The Alignment enumeration code will not be modified.

two。 You don't want to use Alignment to enumerate new features

Then I would recommend your way of handling it. Also, you can define a method for your code like this:

/ / Code # 19 / / See Code # 01 for Alignment. Public static bool IsAlignment (Alignment a) {switch (a) {case Alignment.Left: return true; case Alignment.Center: return true; case Alignment.Right: return true; default: return false;}}

This method is much more efficient than the IsDefine method.

Thank you for your reading, the above is the content of "what is the method of C # enumeration assignment". After the study of this article, I believe you have a deeper understanding of what the method of C # enumeration assignment is. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report