明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

c# enum 枚举名称和ID 互换获取.................

Posted on 2012-05-24 22:32  且行且思  阅读(17973)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;




public partial class Default2 : System.Web.UI.Page
{
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
    enum Direction
    {
        UP = 1,
        RIGHT = 2,
        DOWN = 3,
        LEFT = 4,
    };
    enum Days { Sat = 0, Sun, Mon, Tue, Wed, Thu, Fri };


    protected void Page_Load(object sender, EventArgs e)
    {
        ConvertEnum2DataTable( ((Enum) new Colors() ).GetType());

           int x = (int)Days.Sun; int y = (int)Days.Fri;
            Response.Write("Sun = {0}"+ x);
            Response.Write("Fri = {0}" + y);

            //由枚举enum的名称得到enum的值         
            Response.Write("<br>int: " + (int)Enum.Parse(typeof(Days), "Thu"));
            Response.Write("<br>TT: " +  (Days)Enum.Parse(typeof(Days), "Thu") );

            //根据ID获取枚举名称 1
            Response.Write("eee = {0}" + (Days)y);
            //根据ID获取枚举名称 2
            Response.Write("A:" + Enum.GetName(typeof(Days), y));
          
    }
    private DataTable ConvertEnum2DataTable(Type source)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");

            foreach (string name in Enum.GetNames(source))
            {
                DataRow dr = dt.Rows.Add();
                dr[0] = name;
                dr[1] =(int) Enum.Parse(source, name);
            }
            return dt;
        }
    


}