C#枚舉類型

來源:互聯網
上載者:User

本文轉自:http://tech.ddvip.com/2007-11/119553764137735.html

      內容摘要:對於C#中的枚舉類型不僅可以提高程式的可讀性,而且可以減少因底層值發生改變而導致的程式改動。 

  對於C#中的枚舉類型不僅可以提高程式的可讀性,而且可以減少因底層值發生改變而導致的程式改動。另外一個好處是枚舉類型是強型別,以enum類型作為參數傳遞時,接受方法必須有一個相同的匹配參數;否則編譯器將會報錯。

  枚舉類型的基礎類型可以是除Char外的任何整型。如果沒有顯式聲明基礎類型,則使用Int32。如果沒有為enum符號賦之,系統會自動對其分別賦值為0,1,2,3,等等。

  如果要將枚舉類型賦值給基本類型,則需要顯式強制轉換,如

   intseven=(int)Week.Sunday; //seven=7

 

  下面是一個常式,解釋使用enum怎樣使程式更加清晰易讀:

   enumWeek:int{
    Monday =1;
    Tuesday=2;
    Wednesday=3;
    Thursday=4;
    Friday=5;
    Saturday=6;
    Sunday=7;
   }
         
   staticstringGetDay(Weekday)
  {
     caseWeek.Monday:return("TodayisMonday.");
     caseWeek.Tuesday:return("TodayisTuesday."); 
     caseWeek.Wednesday:return("TodayisWednesday.");
     caseWeek.Thursday:return("TodayisThursday."); 
     caseWeek.Friday:return("TodayisFriday."); 
     caseWeek.Saturday:return("TodayisSaturday."); 
     caseWeek.Sunday:return("TodayisSunday."); 
     default:return("nosuchday");
  }

 

  System.Enum的方法

  System.Enum中三個比較有用的方法是Enum.IsDefined、Enum.Parse和Enum.GetName。

  這三個方法都是staticmethod,前兩種方法常一起使用,用來確定一個值或符號是否是一個枚舉的成員,然後建立它的一個執行個體。

  IsDefined方法有兩個參數:一個是typeof操作符返回的枚舉類型,另一個表示所測試的字串。如果傳遞一個數字之作為第二個參數,這是這個方法的第二種形式,用於測試是否有指定的常量。

  Parse方法選取同樣的參數,並建立枚舉類型的一個執行個體。在使用Parse方法之前,一定要確保該枚舉成員已經存在,否則系統會拋出一個異常。

  GetName方法根據指定值(作為第二個參數傳入)返回枚舉中的相應字串。如

  stringtues=Enum.GetName(typeof(Week),2);    tues=Tuesday

 

  這裡有一個執行個體,用來確定是否包含於給定字串值匹配的符號。如果有,則建立此enum的一個執行個體,並使用方法GetName列印出其中的一個成員值。

  關於Enum的toString方法

  這裡有一個我在CSDN上看到的程式,讀懂這個程式,不僅可以很好的理解關於Enum的toString方法,而且可以很好的理解符號和值之間的關係。

 using System;   class Sample   
 {  
     enum Colors {Red, Green, Blue, Yellow};

     public static void Main()   
     {  
         Colors myColor = Colors.Yellow;

        Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"));  
         Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d")); 
           Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"));  
         Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"));                    Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);                    Console.WriteLine("myColor.ToString("g") = {0}", myColor.ToString("g"));  
         Console.WriteLine("myColor.ToString("G") = {0}", myColor.ToString("G"));                    Console.WriteLine("myColor.ToString("x") = {0}", myColor.ToString("x"));  
         Console.WriteLine("myColor.ToString("X") = {0}", myColor.ToString("X"));                    Console.WriteLine("myColor.ToString("d") = {0}", myColor.ToString("d"));  
         Console.WriteLine("myColor.ToString("D") = {0}", myColor.ToString("D"));                        Console.WriteLine("myColor.ToString("f") = {0}", myColor.ToString("f"));  
         Console.WriteLine("myColor.ToString("F") = {0}", myColor.ToString("F"));  
     }  
 } 
  /*  
 This example produces the following results:  
 Colors.Red = 0  
 Colors.Green = 1  
 Colors.Blue = 2  
 Colors.Yellow = 3   myColor = Colors.Yellow   myColor.ToString("g") = Yellow  
 myColor.ToString("G") = Yellow  
 myColor.ToString("x") = 00000003  
 myColor.ToString("X") = 00000003  
 myColor.ToString("d") = 3  
 myColor.ToString("D") = 3  
 myColor.ToString("f") = Yellow  
 myColor.ToString("F") = Yellow  
 */ 

Enum.ToString 方法 ()    

  傳回值  

  此執行個體的值的字串表示。  

  備忘  

  使用此方法就如同指定了通用格式字元“G”一樣。也就是說,如果未將 FlagsAttribute 應用到此枚舉類型,且存在與此執行個體的值相等的已命名常數,則傳回值為包含該常數名稱的字串。如果應用了 FlagsAttribute,且存在與此執行個體的值相等的一個或多個已命名常數的組合,則傳回值是一個字串,該字串包含用分隔字元分隔的常數名稱列表。其他情況下,傳回值是此執行個體的數值的字串表示形式。  

  有關格式字元的更多資訊,請參見 Format 方法的備忘部分。有關一般格式化的更多資訊,請參見格式化概述。  

  .NET Framework 精簡版 - Windows CE .NET 平台說明:  因為此方法搜尋中繼資料表,所以它大量佔用系統資源,從而可能影響效能。

  樣本  

  [C#]   

 using System;   public class EnumSample {  
     enum Colors {Red = 1, Blue = 2};  
      
     public static void Main() {  
         Enum myColors = Colors.Red;  
         Console.WriteLine("The value of this instance is ’{0}’",  
            myColors.ToString());  
     }  
 }  
 /*  
 Output.  
 The value of this instance is ’Red’.  
 */ 
 

 

  枚舉和位標誌

  我們經常會把枚舉類型的值設定為2的冪值,這是因為枚舉成員經常要做邏輯操作,在這種情況下,這種2的冪值由一個顯著的優點,即它們可以映射到某個二進位位。下面給出一個例子:

 

   enumfabric
    {
      cotton=1,
      silk=2,
      wool=4,
      rayon=8,
  other=128,
    }
      fabricfab=fabric.cotton|fabric.wool;
      Console.WriteLine(fab.ToString());     //output:5

 

  如果輸出結果能把變數表示為wool和cotton的組合,就會更有意思。通過在枚舉中添加[flags]屬性就可以做到。

    [Flags]
    enumfabric
    {
      cotton=1,
      silk=2,
      wool=4,
      rayon=8,
      other=128,
    }
      fabricfab=fabric.cotton|fabric.wool;
      Console.WriteLine(fab.ToString("g"));  //output:cotton,wool

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.