转自:http://www.cnblogs.com/sukyboor/archive/2006/04/22/382173.html
定义枚举成员的时候经常很犯愁.那就是怎么显示的问题.你说成员名称用中文吧
好象显的不够专业,毕竟中文在程序开发了是弱势语言.
public enum SexEnum
{
男 = 0,
女
} 如果向上面这样写的话,极容易被bs,所以在很多时候看到同事们是这么写的
public enum SexEnum
{
men = 0,
women
} 这样写也不行啊,如果显示出来的时候,会显示 性别: women 如果把这样的软件给客户用.准能把客户气吐血.
于是又在这个基础上加个转换函数 GetSexEnumCnName
//获取性别类型的中文名称

private string GetSexEnumCnName(SexEnum sex)
{

switch(sex)
{
case SexEnum.men:
return "男";
case SexEnum.women:
return "女";
}
return "";
} 那还有没有别的解决方法?
昨天晚上为了给
aps加上显示功能,我想到了个比较偷巧的解决方法
一、给枚举类型的各个枚举值加上自定义属性
二、要显示的时候就获得枚举自定义属性
实现方法如下:
using System;
using System.Collections;
using System.ComponentModel;
using SPL.Persister.Attributes;

/**//// <summary>性别</summary>
public enum SexEnum
{
[Description("男")]
men,
[Description("女")]
women,
} Description是System.ComponentModel上自定义的属性.用于指定属性或事件的说明
好了,接下来是显示的工作了.

/**//// <summary>
/// 获取枚举值的详细文本
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public static string GetEnumDescription(object e)

{
//获取字段信息
System.Reflection.FieldInfo[] ms = e.GetType().GetFields();
Type t = e.GetType();
foreach(System.Reflection.FieldInfo f in ms)

{
//判断名称是否相等
if(f.Name != e.ToString())continue;

//反射出自定义属性
foreach(Attribute attr in f.GetCustomAttributes(true))

{
//类型转换找到一个Description,用Description作为成员名称
System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute;
if(dscript != null)
return dscript.Description;
}

}
//如果没有检测到合适的注释,则用默认名称
return e.ToString();
} 使用方法
//显示性别
lbSex.Text = GetEnumDescription(SexEnum.man);



//用下拉列表框显示性别类型
DropDownList ddl =new DropDownList();
foreach(object e in Enum.GetValues(typeof(SexEnum)))
ddl.Items.Add(new ListItem( GetEnumDescription(e),((int)e).ToString())); 看到这里也许有人该问了?性能问题如何解决?我这里提一个方法把"SexEnum.man"作为key,把dscript 缓存起来.................这个简单吧,具体实现我就不写了