程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#的枚舉序列化

c#的枚舉序列化

編輯:C#入門知識

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace ConsoleApplication1
{
    [System.AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
    public class EnumSerializedAttribute : System.Attribute
    {
        private string _serialized;

        public EnumSerializedAttribute(string s)
        {
            this._serialized = s;
        }

        public string GetValue()
        {
            return _serialized;
        }
    }

    public static class MyHelper
    {
        public static string AsString(this Enum o)
        {
            Type t = o.GetType();
            string filedName = Enum.GetName(t, o);
            System.Reflection.FieldInfo f = t.GetField(filedName);
            object[] atts = f.GetCustomAttributes(true);

            for (int i = 0; i < atts.Length; i++)
            {
                object att = atts[i];
                if (att is EnumSerializedAttribute)
                {
                    EnumSerializedAttribute r = (EnumSerializedAttribute)att;
                    return r.GetValue();
                }
            }

            return filedName;
        }
    }

    class Program
    {

        enum Operation
        {
            [EnumSerialized("Enable Serialized")]
            Enable = 1,
            [EnumSerialized("Disable Serialized")]
            Disable = 0,
            Other = 2
        }

        static void Main(string[] args)
        {
            Console.WriteLine(Operation.Disable.AsString());
            Console.WriteLine(Operation.Enable.AsString());
            Console.WriteLine(Operation.Other.AsString());

            Console.Read();
        }
    }
}
 
 
 

摘自  Tim's Blog

  1. 上一頁:
  2. 下一頁: