获取Enum枚举值描述的几法方法
1.定义枚举时直接用中文
由于VS对中文支持的很不错,所以很多程序员都采用了此方案.
缺点:1.不适合多语言 2.感觉不太完美,毕竟大部分程序员大部分代码都使用英文
缺点:不适合多语言
原文:http://www.cnblogs.com/hilite/archive/2006/03/28/360793.html
枚举定义:
[EnumDescription("订单、订单中的产品、产品项的状态。")]
public enum OrderStateEnum
{
[EnumDescription("未开始")]
Ready = 0,
[EnumDescription("进行中")]
Processing,
[EnumDescription("等待中")]
Waiting,
[EnumDescription("取消")]
Canceled,
[EnumDescription("完成")]
Finished
}
代码访问:
0、获得枚举类型的文字描述
string txt = EnumDescription.GetEnumText(typeof(OrderStateEnum));
1、获得某个枚举值的文字描述:
string txt = EnumDescription.GetFieldText(OrderStateEnum.Processing)
2、获得枚举中各个字段的定义数组:
EnumDescription[] des = EnumDescription.GetFieldTexts(typeof(OrderStateEnum))
如果需要排序,通过他的另一个重载
public static EnumDescription[] GetFieldTexts( Type enumType, SortType sortType )
3、绑定到下拉框:
comboBox1.DataSource = EnumDescription.GetFieldTexts(typeof(OrderStateEnum));
comboBox1.ValueMember = "EnumValue";
comboBox1.DisplayMember = "EnumDisplayText";
comboBox1.SelectedValue = (int)OrderStateEnum.Finished; //选中值
EnumDisplayText.cs 源码
using System;
using System.Reflection;
using System.Collections;
using System.Text;
namespace BirdSof
{
/// <summary>
/// 把枚举值按照指定的文本显示
/// <remarks>
/// 一般通过枚举值的ToString()可以得到变量的文本,
/// 但是有时候需要的到与之对应的更充分的文本,
/// 这个类帮助达到此目的
/// Date: 2006-3-25
/// Author: dearzp@hotmail.com
/// </remarks>
/// </summary>
/// <example>
/// [EnumDescription("中文数字")]
/// enum MyEnum
/// {
/// [EnumDescription("数字一")]
/// One = 1,
///
/// [EnumDescription("数字二")]
/// Two,
///
/// [EnumDescription("数字三")]
/// Three
/// }
/// EnumDescription.GetEnumText(typeof(MyEnum));
/// EnumDescription.GetFieldText(MyEnum.Two);
/// EnumDescription.GetFieldTexts(typeof(MyEnum));
/// </example>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum)]
public class EnumDescription : Attribute
{
private string enumDisplayText;
private int enumRank;
private FieldInfo fieldIno;
/// <summary>
/// 描述枚举值
/// </summary>
/// <param name="enumDisplayText">描述内容</param>
/// <param name="enumRank">排列顺序</param>
public EnumDescription( string enumDisplayText, int enumRank )
{
this.enumDisplayText = enumDisplayText;
this.enumRank = enumRank;
}
/// <summary>
/// 描述枚举值,默认排序为5
/// </summary>
/// <param name="enumDisplayText">描述内容</param>
public EnumDescription( string enumDisplayText )
: this(enumDisplayText, 5) { }
public string EnumDisplayText
{
get { return this.enumDisplayText; }
}
public int EnumRank
{
get { return enumRank; }
}
public int EnumValue
{
get { return (int)fieldIno.GetValue(null); }
}
public string FieldName
{
get { return fieldIno.Name; }
}
#region =========================================对枚举描述属性的解释相关函数
/// <summary>
/// 排序类型
/// </summary>
public enum SortType
{
/// <summary>
///按枚举顺序默认排序
/// </summary>
Default,
/// <summary>
/// 按描述值排序
/// </summary>
DisplayText,
/// <summary>
/// 按排序熵
/// </summary>
Rank
}
private static System.Collections.Hashtable cachedEnum = new Hashtable();
/// <summary>
/// 得到对枚举的描述文本
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static string GetEnumText( Type enumType )
{
EnumDescription[] eds = (EnumDescription[])enumType.GetCustomAttributes(typeof(EnumDescription), false);
if ( eds.Length != 1 ) return string.Empty;
return eds[0].EnumDisplayText;
}
/// <summary>
/// 获得指定枚举类型中,指定值的描述文本。
/// </summary>
/// <param name="enumValue">枚举值,不要作任何类型转换</param>
/// <returns>描述字符串</returns>
public static string GetFieldText( object enumValue )
{
EnumDescription[] descriptions = GetFieldTexts(enumValue.GetType(), SortType.Default);
foreach ( EnumDescription ed in descriptions )
{
if ( ed.fieldIno.Name == enumValue.ToString() ) return ed.EnumDisplayText;
}
return string.Empty;
}
/// <summary>
/// 得到枚举类型定义的所有文本,按定义的顺序返回
/// </summary>
/// <exception cref="NotSupportedException"></exception>
/// <param name="enumType">枚举类型</param>
/// <returns>所有定义的文本</returns>
public static EnumDescription[] GetFieldTexts( Type enumType )
{
return GetFieldTexts(enumType, SortType.Default);
}
/// <summary>
/// 得到枚举类型定义的所有文本
/// </summary>
/// <exception cref="NotSupportedException"></exception>
/// <param name="enumType">枚举类型</param>
/// <param name="sortType">指定排序类型</param>
/// <returns>所有定义的文本</returns>
public static EnumDescription[] GetFieldTexts( Type enumType, SortType sortType )
{
EnumDescription[] descriptions = null;
//缓存中没有找到,通过反射获得字段的描述信息
if ( cachedEnum.Contains(enumType.FullName) == false )
{
FieldInfo[] fields = enumType.GetFields();
ArrayList edAL = new ArrayList();
foreach ( FieldInfo fi in fields )
{
object[] eds = fi.GetCustomAttributes(typeof(EnumDescription), false);
if ( eds.Length != 1 ) continue;
((EnumDescription)eds[0]).fieldIno = fi;
edAL.Add(eds[0]);
}
cachedEnum.Add(enumType.FullName, (EnumDescription[])edAL.ToArray(typeof(EnumDescription)));
}
descriptions = (EnumDescription[])cachedEnum[enumType.FullName];
if ( descriptions.Length <= 0 ) throw new NotSupportedException("枚举类型[" + enumType.Name + "]未定义属性EnumValueDescription");
//按指定的属性冒泡排序
for ( int m = 0; m < descriptions.Length; m++ )
{
//默认就不排序了
if ( sortType == SortType.Default ) break;
for ( int n = m; n < descriptions.Length; n++ )
{
EnumDescription temp;
bool swap = false;
switch ( sortType )
{
case SortType.Default:
break;
case SortType.DisplayText:
if ( string.Compare(descriptions[m].EnumDisplayText, descriptions[n].EnumDisplayText) > 0 ) swap = true;
break;
case SortType.Rank:
if ( descriptions[m].EnumRank > descriptions[n].EnumRank ) swap = true;
break;
}
if ( swap )
{
temp = descriptions[m];
descriptions[m] = descriptions[n];
descriptions[n] = temp;
}
}
}
return descriptions;
}
#endregion
}
}
下载地址:原文下载
3.NBear提供的绑定Enum到ASP.NET数据绑定控件的完美解决方案(博客园-Teddy)
(支持第三方枚举描述,支持二进制与过的枚举值)
原文:http://www.cnblogs.com/teddyma/archive/2007/05/25/759842.html
EnumDescriptionAttribute.cs 源码
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace NBear.Common
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false, Inherited=true)]
public class EnumDescriptionAttribute : Attribute
{
private string defaultDesc;
public string DefaultDescription
{
get
{
return defaultDesc;
}
set
{
defaultDesc = value;
}
}
public virtual string GetDescription(object enumValue)
{
Check.Require(enumValue != null, "enumValue could not be null.");
return DefaultDescription ?? enumValue.ToString();
}
public static string GetDescription(Type enumType, int enumIntValue)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Dictionary<int, string> descs = EnumDescriptionAttribute.GetDescriptions(enumType);
Dictionary<int, string>.Enumerator en = descs.GetEnumerator();
while (en.MoveNext())
{
if ((enumIntValue & en.Current.Key) == en.Current.Key)
{
if (sb.Length == 0)
{
sb.Append(en.Current.Value);
}
else
{
sb.Append(',');
sb.Append(en.Current.Value);
}
}
}
return sb.ToString();
}
public static Dictionary<int, string> GetDescriptions(Type enumType)
{
Check.Require(enumType != null && enumType.IsEnum, "enumType must be an enum type.");
FieldInfo[] fields = enumType.GetFields();
Dictionary<int, string> descs = new Dictionary<int, string>();
for (int i = 1; i < fields.Length; ++i)
{
object fieldValue = Enum.Parse(enumType, fields[i].Name);
object[] attrs = fields[i].GetCustomAttributes(true);
bool findAttr = false;
foreach (object attr in attrs)
{
if (typeof(EnumDescriptionAttribute).IsAssignableFrom(attr.GetType()))
{
descs.Add((int)fieldValue, ((EnumDescriptionAttribute)attr).GetDescription(fieldValue));
findAttr = true;
break;
}
}
if (!findAttr)
{
descs.Add((int)fieldValue, fieldValue.ToString());
}
}
return descs;
}
}
}
使用方法:
枚举定义(普通)
public enum SimpleStatus
{
[NBear.Common.EnumDescription(DefaultDescription="Desc of Value1")]
Value1 = 1,
[NBear.Common.EnumDescription(DefaultDescription="Desc of Value2")]
Value2 = 2
}
枚举定义(继承)
public class MyEnumDescriptionAttribute : NBear.Common.EnumDescriptionAttribute
2 {
3 private static string[] customDescs = new string[] { "custom desc of Value1", null }; //the second value is null here to use the DefaultDescription set in enum definition
4
5 public override string GetDescription(object enumValue)
6 {
7 return customDescs[(int)enumValue] ?? base.GetDescription(enumValue);
8 }
9 }
使用EnumDescriptionAttribute以透明获取的枚举值描述信息。
调用EnumDescriptionAttribute.GetDescriptions(enumType)这个静态方法就可以得到指定枚举类型的所有枚举值的由EnumDescriptionAttribute或其继承类标注的描述信息。