Learning C # Enum

Source: Internet
Author: User

In the long run, creating enumeration can save a lot of time and reduce a lot of trouble. Enumeration has at least three advantages over unformatted integers:

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

● Enumeration makes the code clearer. descriptive names can be used to represent integer values rather than fuzzy numbers.

● Enumeration makes the code easier to type. When assigning values to enumeration instances, vs. Net ide uses intelliisense to pop up a list box containing acceptable values, which reduces the number of buttons and allows us to recall possible values.

Public Enum filestates {begin = 1, pause = 2, rollback = 3, success = 4 };
All enumeration types are value types. System. Enum is an abstract class. All enumeration types inherit from it directly, and of course all its members. All value types are system. the descendant of valuetype, And the enumeration type is no exception. The Enumeration type is directly inherited from system. enum, while system. the enum is directly inherited from the system. valuetype, so the enumeration type is also system. the descendant of valuetype.
The value types are all descendants of system. valuetype ", but the descendants of system. valuetype are not all value types, and system. Enum is the only special case! Among all the descendants of system. valuetype, all except system. Enum are value types. In fact, we can find the declaration of system. Enum in the source code of. Net: public abstract class Enum: valuetype, icomparable, iformattable, iconvertible

  • 1. All enumeration types (Enum type) are value types.
  • 2. system. Enum and system. valuetype are reference types.
  • 3. The Enum type is implicitly directly inherited from system. Enum, and the inheritance relationship can only be automatically expanded by the compiler. However, system. Enum is not an enumeration type ).
  • 4. system. Enum is a special case. It inherits directly from system. valuetype, but it is a reference type.

A: enumeration types can be boxed into system. Enum, system. valuetype, system. Object, system. iconvertible, system. iformattable, and system. icomparable.

Note: In.. NET 1.1, the enumeration type can only be boxed to system. enum, system. valuetype, system. object.. NET 2.0, the enumeration type can also be boxed to system. the three interfaces implemented by Enum: system. iconvertible, system. icomparable, system. iformattable. The corresponding packing operation can be either implicit or explicit.

The enumerated type has a certain relationship with the integer type. In fact, each Enumeration type corresponds to an integer type, which is called underlying type by default ,. net using system. int32. Of course, you can manually specify it as another Integer type:
The underlying types that can be specified as enumeration can only be integer types listed below: byte, sbyte, short, ushort, Int, uint, long, ulong.

If you do not manually specify the value of a member, from the top down, the values of each member are: 0, 1, 2 ,.... It is a non-negative integer series with an initial value of 0 and step size of 1. For example:
Public Enum alignment
{
Left, // 0
Center, // 1
Right // 2
}

The value of the assigned member is the value you specify. Of course, no matter whether you manually specify the enumerated member value or not, the incremental step will not change, always 1. To test whether you understand it or not, please state the values of the following enumerated members and the reason for your judgment (use the human brain rather than the computer to run the following code ):
Public Enum drivetype: sbyte
{
CDROM,
Fixed =-2,
Network,
Norootdirectory =-1,
Ram,
Removable = Network * norootdirectory,
Unknown
}

Public Enum customerkind
{
Normal = 90,
VIP = 80,
Supervip = 70,
Inactive = 100
}

Public Class Customer
{
Public readonly customerkind kind;

Private double m_payment;
Public double payment
{
Return m_payment * (INT) kind/100;
}

Each member of customerkind is assigned a specific value, which is actually the percentage of the customer's discount. In the customer class, the payment attribute obtains the enumerated Member values (that is, the shopping discount rate) through forced type conversion and is used for payment calculation. It can be seen from this that the values of retrieved enumerated members can also be converted by a strongly-typed conversion method.

// Code here
}

The enumerated type can be forcibly converted to an integer, or an integer can be forcibly converted to an enumerated type.
Alignment A = (alignment) 1; but this mechanism may cause you some trouble.
Public static bool isalignment (alignment)
{
Switch ()
{
Case alignment. left:
Case alignment. Center:
Case alignment. Right:
Return true;
Default:
Return false;
}

}

Convert (parses) Enumeration type to string type
The simplest method is to use public override string tostring () of system. Enum; or convert the enumeration type to the iconvertible interface, and then call the string tostring (iformatprovider provider) of this interface );

Static void main ()
{
Alignment A = Alignment. Right;
Console. writeline ("alignment is {0}.", A. tostring ());

Fontstyle FS = fontstyle. Bold | fontstyle. Underline;
Console. writeline ("fontstyle is {0}.", FS. tostring ());
}

Manually specify the format parameter: console. writeline ("alignment is {0}.", A. tostring ("D "));

How to resolve a string that represents an enumeration member to a corresponding Enumeration type:
In this case, you need system. Enum's public static object parse (type enumtype, string value, bool ignorecase );

Static void main ()
{
String name = "right ";
Alignment A = (alignment) enum. parse (typeof (alignment), name, false );

Console. writeline (A. tostring ());

String names = "bold, italic, underline ";
Fontstyle FS = (fontstyle) enum. parse (typeof (fontstyle), names, false );

Console. writeline (FS. tostring ());
}

Enumeration should not be used:
Enumeration represents a stable classification standard. When you look at the enumeration types in. NET Framework BCl, you will find that they have almost no possibility or trend change, and show a kind of stability. Therefore, when the classification standard you want to express is also stable, you can consider the enumeration type. So under what circumstances do I not use enumeration? Generally, when the classification criteria are not closed-that is, new subcategories may be generated at any time or existing subcategories may be replaced at any time-you should consider using other expressions.

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.