c#枚舉轉化樣本大全,數字或字串轉枚舉

來源:互聯網
上載者:User

枚舉轉化樣本大全,數字或字串轉枚舉,本文重點舉例說明C#枚舉的用法,數字轉化為枚舉、枚舉轉化為數字及其枚舉數值的判斷,以下是具體的樣本:

 

字串轉換成枚舉:DayOfWeek week= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Friday"); 數字轉換成枚舉:DayOfWeek week= (DayOfWeek)5;  //Friday 具體的樣本: 定義枚舉: public enum DisplayType {   All=10,   Up=20,   Down=30 }

 

1.數值轉化 (1)字元轉化為枚舉 string str="up"; DisplayType displayType; displayType=(DisplayType)System.Enum.Parse(typeof(DisplayType),str,true); Response.Write(displayType.ToString());

結果是:Up Enum.Parse 方法第3個參數,如果為 true,則忽略大小寫;否則考慮大小寫。

(2)數字轉化為枚舉 int i=30; DisplayType displayType; displayType=(DisplayType)System.Enum.Parse(typeof(DisplayType),i.ToString()); Response.Write(displayType.ToString()); 結果是:Down (3)枚舉轉化為字元 DisplayType displayType=DisplayType.Down; string str=displayType.ToString(); Response.Write(str); 結果是:Down

(4)枚舉轉化為數字 方法一: DisplayType displayType=DisplayType.Down; int i=Convert.ToInt32(displayType.ToString("d")); Response.Write(i.ToString());

或者:(int)Enum.Parse(typrof(DisplayType),"Down") 結果是:30

方法二: DisplayType displayType=DisplayType.Down; int i=((IConvertible)((System.Enum)displayType)).ToInt32(null); Response.Write(i.ToString()); 結果是:30

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.