15th Zhang Yi type and bit flags

Source: Internet
Author: User

Enumeration offers some very cool features that most developers are unfamiliar with. These new features greatly simplify the development of the application.

15.1 enum Types

The enumeration type (enumerated types) defines a set of "symbol name/value" pairs.

The following color types define a set of symbols, each of which identifies a color:

Internal enum color{White        ,// assigned 0        Red,  // assigned 1        greed,//  assigned value 2        // Assignment 3        Orange// assignment 4}

Of course, we can also write a program with 0 for White, 1 for red, and so on.

However, these numbers should not be hardcoded into the code, but should be swapped with the enumeration type because:

    • Enumeration types make it easier for programs to write, read, and maintain.
    • Enum types are strongly typed.

Each enumeration type is derived directly from System.Enum, which derives from System.ValueType. And System.ValueType is derived from System.Object. Therefore, enum types are value types, which can be represented as unboxed and boxed forms. Unlike other value types, enumeration types cannot define any methods, properties, and events.

When compiling enumeration types, the C # compiler converts each symbol into a constant field of type. For example, the compiler would consider the preceding color enumeration type as the following code:

But the C # compiler does not actually compile the above code because it prohibits the definition of a type derived from a particular type of System.Enum.

The symbol defined by an enumeration type is a constant value, so when the C # compiler discovers that a symbol of an enumeration type is referenced in the code, it replaces the symbol at compile time with a numeric value, and the code no longer references the enumeration type that defines the symbol.

Simply put, an enumeration type is simply a structure that defines a set of constant fields and an instance field. Constant fields are embedded in the assembly's metadata and can be accessed through reflection. This means that at run time, all the symbols associated with an enumeration type and their values are obtained. It also means that we can convert a string symbol to its corresponding value.

Here are some of the main ways to discuss the System.Enum type:

Getunderlyingtype:

 Public Static Type Getunderlyingtype (type enumtype);

The method returns the underlying type used to hold the value of an enumerated type. Each enum type has an underlying type, which can be byte,short,int (the most commonly used, also the C # default selection), long, and so on.

Attention:

    • C # requires that only primitive type names can be specified, and if an FCL type name (such as Int32) is used, an error is given.
    • The enumeration type we define should be the same sibling as the one that needs to call it.

The following code demonstrates how to declare an enumeration type that has an underlying type of byte:

Internal enum byte {white        ,        Red,        greed,        Blue,        Orange}staticvoid  Main () {            Console.WriteLine (Enum.getunderlyingtype (typeof//System.Byte}

typeof () and GetType () differences in C #:

    • X in typeof (X) must be a specific class name, type name, and so on, and cannot be a variable name.
    • The GetType () method inherits from object, so any object in C # has the GetType () method, and its function is the same as typeof (), which returns the type of the current object of type.

The C # compiler treats enumeration types as primitive types, so we can manipulate an instance of an enumeration type using many familiar operators (==,!=,<,>,<=,>=,+,-, ^,&,|,++,--). All of these operators actually make use of Value_ instance fields inside each instance of an enumeration type.

Tostring:

 Public string ToString (string format);

Given an instance of an enumeration type, we can invoke the ToString method inherited from System.Enum.

     Public Static classProgram {Static voidMain () {Color C=Color.Blue; Console.WriteLine (C.tostring ());//"Blue" General formatConsole.WriteLine (C.tostring ("G"));//"Blue" General formatConsole.WriteLine (C.tostring ("D"));//"3" decimal formatConsole.WriteLine (C.tostring ("X"));//"03" hexadecimal format        }    }    Internal enumColor:byte{white, Red, greed, Blue, Orange}

Format:

 Public Static string Object string format);

It can be called to format a value of an enumerated type.

Console.WriteLine (Enum.format (typeof3"G")); // Show "Blue"

GetValues:

 Public Static Array GetValues (Type enumtype);

Gets all the symbols defined in the enumeration type and their corresponding values.

color[] colors = (color[]) enum.getvalues (typeof(Color)); Console.WriteLine ("number ofsymbols defined:" + colors. Length); Console.WriteLine ("value\tsymbol\n-----\ t------"); foreach inch colors) {    Console.WriteLine ("{0,5:d}\t{0:g}", C);}

GetName:

 Public Static string object value);

Returns a string representation of a numeric value.

Enum.getname (typeof3); // "Blue"

GetNames:

 Public Static string [] GetNames (Type enumtype);

Returns a string array with each symbol representing a string.

Enum.getnames (typeof(Color)); // {string[5]} // [0]: "White" // [1]: "Red" // [2]: "Greed" // [3]: "Blue" // [4]: "Orange"

Parse:

 Public Static Object string bool ignoreCase)

Converts a symbol to an instance of an enumeration type.

Color c = (color) enum.parse (typeof"Orange"true//Orange Enum.parse (typeof"0"true); //  White

TryParse:

 Public Static BOOL Tryparse<tenum> (stringbooloutwherestruct;

Converts the string representation of the name or numeric value of one or more enumeration constants to an equivalent enumeration object. The return value used to indicate whether the conversion succeeded.

The TryParse method is similar to the parse method, except that the TryParse method does not throw an exception if the conversion fails.

bool a=enum.tryparse<color> ("Brown"false out C); // false, Brown is not defined in the enumeration

Isdefine:

 Public Static BOOL object value);

Determines whether a value is valid for an enumeration type.

enum.isdefined (typeof"white"); // false to perform a case-sensitive check enum.isdefined (typeof5); // false, the color enum type does not have a symbol corresponding to 5

15th Zhang Yi type and bit flags

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.