zoukankan      html  css  js  c++  java
  • (C#)枚举 Enumerations

    (C#)枚举.


    枚举是由程序员定义的类型。
    - 与结构一样,枚举是值类型,因此直接存储他们的数据,而不是分开存储成引用和数据.
    - 枚举只有一种类型的成员:整数值常量.
    - 每个枚举类型都有一个底层整数类型(默认为int). 编译器把第一个成员赋值为0,并对每个后续成员赋值比前一个成员多1.

    C#代码  收藏代码
    1. enum TrafficLight{  
    2.  Green,     //用逗号分隔,会自动转换为int型 0 ,  
    3.  Yellow,    // 1  
    4.  Red        // 2  
    5. }  

    可以把枚举值(成员值)付给枚举类型变量,或者从另一个相同类型的变量复制值.

    C#代码  收藏代码
    1. enum TrafficLight  
    2. {  
    3.     Green,  
    4.     Yellow,  
    5.     Red  
    6. }  
    7.   
    8. namespace ConsoleApplication1  
    9. {  
    10.     class Program  
    11.     {  
    12.         static void Main()  
    13.         {  
    14.             TrafficLight t1 = TrafficLight.Red;  
    15.             TrafficLight t2 = TrafficLight.Green;  
    16.             TrafficLight t3 = t2;  
    17.   
    18.             Console.WriteLine(t1);  
    19.             Console.WriteLine(t2);  
    20.             Console.WriteLine(t3);  
    21.         }  
    22.     }  
    23. }  

    输出: 
    Red
    Green
    Green

    枚举默认的为隐式编号.0,1,2,...
    但是枚举也支持设置底层类型和显示编号,例如:

    C#代码  收藏代码
    1. enum TrafficLight : int  
    2. {  
    3.     Green = 0,  
    4.     Yellow = 1,  
    5.     Red =2  
    6. }  

    下面研究一下如何获取enum的名称和值。

    namespace ConsoleApplication3
    {
        enum TrafficLight
        {
            Green = 1,
            Yellow,
            Red
        }
        class Program
        {
            static void Main()
            {
                TrafficLight t1 = TrafficLight.Green;
                TrafficLight t2 = TrafficLight.Yellow;
                TrafficLight t3 = TrafficLight.Red; 
    
                // 1. Display the name of each enum. 
                Console.WriteLine(t1);      // Output: Green
                Console.WriteLine(t2);      // Output: Yellow
                Console.WriteLine(t3);      // Output: Red
    
                // All enums are instances of the System.Enum type. You cannot derive new classes from System.Enum,
                // but you can use its methods to discover information about and manipulate values in an enum instance.
                string secondEnum = Enum.GetName(typeof(TrafficLight), 2);
                Console.WriteLine(" The second enum name is: {0}", secondEnum);   // Output: Yellow 
    
                secondEnum = TrafficLight.Yellow.ToString();  // Not recommended.
    
                foreach (string enumName in Enum.GetNames(typeof(TrafficLight)))
                {
                    Console.WriteLine ("The enum name is: {0}", enumName);         
                }
    
    
                // 2. Get the value of each enum. 
                Console.WriteLine((int)t2);   // Output:  2 
                Console.WriteLine(t2.GetHashCode());  // Output: 2 
                Console.WriteLine(Convert.ToInt32(t2));    // Output: 2
    
                foreach (int enumValue in Enum.GetValues(typeof(TrafficLight)))
                {
                    Console.WriteLine("The enum value is: {0}", enumValue);
                }
              
                Console.Read();
            }
        }
    }


    Enum为枚举提供基类,其基础类型可以是除 Char 外的任何整型。如果没有显式声明基础类型,则使用 Int32。编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举。

    注意:枚举类型的基类型是除 Char 外的任何整型,所以枚举类型的值是整型值。

    Enum 提供一些实用的静态方法:

    (1)比较枚举类的实例的方法

    (2)将实例的值转换为其字符串表示形式的方法

    (3)将数字的字符串表示形式转换为此类的实例的方法

    (4)创建指定枚举和值的实例的方法。

    举例:enum Colors { Red, Green, Blue, Yellow };

    Enum-->String

    (1)利用Object.ToString()方法:如Colors.Green.ToString()的值是"Green"字符串;

    (2)利用Enum的静态方法GetName与GetNames:

    public static string GetName(Type enumType,Object value)

    public static string[] GetNames(Type enumType)

    例如:Enum.GetName(typeof(Colors),3))与Enum.GetName(typeof(Colors), Colors.Blue))的值都是"Blue"

    Enum.GetNames(typeof(Colors))将返回枚举字符串数组。

    Enum-->List or Array.

    var valuesAsList =Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList();  // or ToArray(); 

    String-->Enum

    (1)利用Enum的静态方法Parse:

    public static Object Parse(Type enumType,string value)

    例如:(Colors)Enum.Parse(typeof(Colors), "Red")

    Enum-->Int

    (1)因为枚举的基类型是除 Char 外的整型,所以可以进行强制转换。

    例如:(int)Colors.Red, (byte)Colors.Green

    Int-->Enum

    (1)可以强制转换将整型转换成枚举类型。

    例如:Colors color = (Colors)2 ,那么color即为Colors.Blue

    (2)利用Enum的静态方法ToObject。

    public static Object ToObject(Type enumType,int value)

    例如:Colors color = (Colors)Enum.ToObject(typeof(Colors), 2),那么color即为Colors.Blue

    判断某个整型是否定义在枚举中的方法:Enum.IsDefined

    public static bool IsDefined(Type enumType,Object value)

    例如:Enum.IsDefined(typeof(Colors), n))

    Enum.HasFlag 方法

    确定当前实例中是否设置了一个或多个位域。

    public bool HasFlag(
    	Enum flag
    )

    using System;
    
    [Flags] public enum Pet {
       None = 0,
       Dog = 1,
       Cat = 2,
       Bird = 4,
       Rabbit = 8,
       Other = 16
    }
    
    public class Example
    {
       public static void Main()
       {
          Pet[] petsInFamilies = { Pet.None, Pet.Dog | Pet.Cat, Pet.Dog };
          int familiesWithoutPets = 0;
          int familiesWithDog = 0;
    
          foreach (Pet petsInFamily in petsInFamilies)
          {
             // Count families that have no pets.
             if (petsInFamily.Equals(Pet.None))
                familiesWithoutPets++;
             // Of families with pets, count families that have a dog.
             else if (petsInFamily.HasFlag(Pet.Dog))
                familiesWithDog++;
          }
          Console.WriteLine("{0} of {1} families in the sample have no pets.", 
                            familiesWithoutPets, petsInFamilies.Length);   
          Console.WriteLine("{0} of {1} families in the sample have a dog.", 
                            familiesWithDog, petsInFamilies.Length);   
       }
    }
    // The example displays the following output:
    //       1 of 3 families in the sample have no pets.
    //       2 of 3 families in the sample have a dog.

     获取枚举的个数:

    方法一:

    System.Enum.GetNames(typeof(MyEnum)).Length

    方法二:

    enum myEnumTest{sat,sun,mon}

    int enumlength = typeof(myEnumTest).GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Length;

    设置 Flag 属性:

    The flags attribute should be used whenever the enumerable represents a collection of flags, rather than a single value. Such collections are usually manipulated using bitwise operators, for example:

    myProperties.AllowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;

    Note that [Flags] by itself doesn't change this at all - all it does is enable a nice representation by the.ToString() method:

    [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
    enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
    
    ...
    
    var str1 = (Suits.Spades | Suits.Diamonds).ToString();
               // "5"
    var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
               // "Spades, Diamonds"

    It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.

    Incorrect declaration:

    [Flags]
    public enum MyColors
    {
        Yellow,
        Green,
        Red,
        Blue
    }

    The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless for use as flags.

    Here's an example of a correct declaration:

    [Flags]
    public enum MyColors
    {
        Yellow = 1,
        Green = 2,
        Red = 4,
        Blue = 8
    }

    To retrieve the distinct values in you property one can do this

    if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
    {
        // Yellow has been set...
    }
    
    if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
    {
        // Green has been set...
    }

    or, in .NET 4 and later,

    if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
    {
        // Yellow has been set...
    }

    Under the covers

    This works because you previously used multiples of two in you enumeration. Under the covers your enumeration values looks like this (presented as bytes, which has 8 bits which can be 1's or 0's)

     Yellow: 00000001
     Green:  00000010
     Red:    00000100
     Blue:   00001000

    Likewise, after you've set your property AllowedColors to Red, Green and Blue (which values where OR'ed by the pipe |), AllowedColors looks like this

    myProperties.AllowedColors: 00001110

    So when you retreive the value you are actually bitwise AND'ing the values

    myProperties.AllowedColors: 00001110
                 MyColor.Green: 00000010
                 -----------------------
                                00000010 // Hey, this is the same as MyColor.Green!

    The None = 0 value

    And regarding use 0 in you enumeration, quoting from msdn:

    [Flags]
    public enum MyColors
    {
        None = 0,
        ....
    }

    Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

    You can find more info about the flags attribute and its usage at msdn and designing flags at msdn

  • 相关阅读:
    常用head标签
    php自定义配置文件简单写法
    sublimeText常用插件
    addslashes,htmlspecialchars,htmlentities转换或者转义php特殊字符防止xss攻击以及sql注入
    服务器安装node全教程
    Sublime Text 3 Build 3176 License
    [转]Zend Studio 文件头和方法注释设置
    给php代码添加规范的注释phpDocumentor
    [转]php 在各种web服务器的运行模式
    .htaccess文件url重写小记
  • 原文地址:https://www.cnblogs.com/fdyang/p/2964508.html
Copyright © 2011-2022 走看看