有关 C# 枚举的几个例子
本文导语: 命名空间: using System.Runtime.Serialization; using System.Reflection; 1.定义枚举 代码如下: /// /// 银行简码 /// [DataContract] public enum BankCode { [EnumMember] [Description("中行")] boc = 95559, [EnumMember] [Description("...
命名空间:
using System.Runtime.Serialization;
using System.Reflection;
1.定义枚举
///
/// 银行简码
///
[DataContract]
public enum BankCode
{
[EnumMember]
[Description("中行")]
boc = 95559,
[EnumMember]
[Description("工行")]
icbc = 95588,
[EnumMember]
[Description("交行")]
comm = 95566
}
2.将枚举转换为DataTable,并读取枚举的描述(Description)值
///
/// 将枚举转换为DataTable
///
///
///
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;
}
///
/// 读取枚举的Description
///
/// 枚举Type
/// 需要读取
///
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
{
int result = 0;
switch (bankCode)
{
case BankCode.boc:
{
result = (int)BankCode.boc;
break;
}
case BankCode.comm:
{
result = (int)BankCode.comm;
break;
}
case BankCode.icbc:
{
result = (int)BankCode.icbc;
break;
}
}
return result;
}
方法B
{
foreach (var item in Enum.GetNames(typeof(BankCode)))
{
if (item == bankCode)
{
return (int) Enum.Parse(typeof (BankCode), item);
}
}
return 0;
}
备注:
A,B两种方法
其中A方法的略处在于当枚举如增加时,需要更改方法。
另B方法,则无需更改。