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();
}
}
}
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();
}
}
}
大家还有没有更好的思路和方法?