代码改变世界

关于枚举enum的tostring方法不能重写的一种替代方案

2009-05-02 17:18  kenty06  阅读(1224)  评论(0编辑  收藏  举报

本文内容来源 http://blogs.msdn.com/abhinaba/archive/2005/10/20/483000.aspx

 

在.net 中,枚举的ToString 方法不能够被重写,有时候我们不想直接显示枚举的标识的时候,想已另一种方式替代显示内容,就可以采取下面介绍的这种方式来实现。

using System;

using System.Reflection;

enum Coolness : byte
{

    [Description("Not so cool")]

    NotSoCool = 5,

    Cool, // since description same as ToString no attr are used

    [Description("Very cool")]

    VeryCool = NotSoCool + 7,

    [Description("Super cool")]

    SuperCool

}

 

class Description : Attribute
{

    public string Text;

    public Description(string text)
    {

        Text = text;

    }
}

class Program

{

static string GetDescription(Enum en)

{

Type type = en.GetType();

MemberInfo[] memInfo = type.GetMember(en.ToString());

if (memInfo != null && memInfo.Length > 0)

{

object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description),
false
);

if (attrs != null && attrs.Length > 0)

return ((Description)attrs[0]).Text;

}

return en.ToString();

}

static void Main(string[] args)

{

Coolness coolType1 = Coolness.Cool;

Coolness coolType2 = Coolness.NotSoCool;

Console.WriteLine(GetDescription(coolType1));

Console.WriteLine(GetDescription(coolType2));

}

}