命名空间:
using System.Runtime.Serialization;
using System.Reflection;
1.定义枚举
/// <summary>
/// 银行简码
/// </summary>
[DataContract]
public enum BankCode
{
[EnumMember]
[Description("中行")]
boc = 95559,
[EnumMember]
[Description("工行")]
icbc = 95588,
[EnumMember]
[Description("交行")]
comm = 95566
}
2.将枚举转换为DataTable,并读取枚举的描述(Description)值
/// <summary>
/// 将枚举转换为DataTable
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static DataTable ConvertEnumToDataTable(Type source)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("value");
dt.Columns.Add("Desc");
foreach (string name in Enum.GetNames(source))
{
object enumValue = Enum.Parse(source, name);
DataRow dr = dt.Rows.Add();
dr[0] = name;
dr[1] = (int)enumValue;
dr[2] = GetEnumDesc(source, name);
}
return dt;
}
/// <summary>
/// 读取枚举的Description
/// </summary>
/// <param name="source">枚举Type</param>
/// <param name="enumName">需要读取</param>
/// <returns></returns>
public static string GetEnumDesc(Type source,string enumName)
{
FieldInfo[] fieldinfo = source.GetFields();
foreach (FieldInfo item in fieldinfo)
{
if (item.Name != enumName) continue;
Object[] obj = item.GetCustomAttributes(typeof (DescriptionAttribute), false);
if (obj.Length == 0) continue;
DescriptionAttribute desc = (DescriptionAttribute) obj[0];
return desc.Description;
}
return enumName;
}
调用示例:DataTable dt = ConvertEnumToDataTable(typeof (BankCode));
3.根据枚举读取枚举值
方法A
方法B
备注:
A,B两种方法
其中A方法的略处在于当枚举如增加时,需要更改方法。
另B方法,则无需更改。