这里定义一个枚举如下:
/**/
/// <summary>
/// 用户状态枚举
/// </summary>
[Flags]
public enum UserFlag
... {
[Description("启用")]
UnForbidden = 1,
[Description("禁用")]
Forbidden = 2,
[Description("删除")]
Deleted = 4
}
/// 用户状态枚举
/// </summary>
[Flags]
public enum UserFlag
... {
[Description("启用")]
UnForbidden = 1,
[Description("禁用")]
Forbidden = 2,
[Description("删除")]
Deleted = 4
}
下面定义两个枚举类型操作函数:
/**/ /// <summary>
/// 根据枚举类型返回类型中的所有值,文本及描述
/// </summary>
/// <param name="type"></param>
/// <returns>返回三列数组,第0列为Description,第1列为Value,第2列为Text</returns>
public static List < string [] > GetEnumOpt(Type type)
... {
List<string[]> Strs = new List<string[]>();
FieldInfo[] fields = type.GetFields();
for (int i = 1, count = fields.Length; i < count; i++)
...{
string[] strEnum = new string[3];
FieldInfo field = fields[i];
//值列
strEnum[1] = ((int)Enum.Parse(type, field.Name)).ToString();
//文本列赋值
strEnum[2] = field.Name;
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
...{
strEnum[0] = field.Name;
}
else
...{
DescriptionAttribute da = (DescriptionAttribute)objs[0];
strEnum[0] = da.Description;
}
Strs.Add(strEnum);
}
return Strs;
}
/**/ /// <summary>
/// 获取枚举类子项描述信息
/// </summary>
/// <param name="enumSubitem">枚举类子项</param>
public static string GetEnumDescription( object enumSubitem)
... {
enumSubitem=(Enum)enumSubitem;
string strValue = enumSubitem.ToString();
FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);
if (fieldinfo != null)
...{
Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
...{
return strValue;
}
else
...{
DescriptionAttribute da = (DescriptionAttribute)objs[0];
return da.Description;
}
}
else
...{
return "不限";
}
}
其中 public static List<string[]> GetEnumOpt(Type type) 函数为获取一个枚举类型所有选项并添加到List<string[]>中,为前台控件绑定提供数据源,前台示例代码如下:
List<string[]> strEnums = EnumDefine.GetEnumOpt(typeof(EnumDefine.UserFlag));
foreach (string[] strEnum in strEnums)
{
ddlUserType.Items.Add(new ListItem(strEnum[0], strEnum[1]));
}
而 public static string GetEnumDescription(object enumSubitem)函数则为获取某一项文字描述信息项函数,前台可以通过调用该类型值,获取该类型的文字描述,示例代码如下:
EnumDefine.GetEnumDescription(UserFlag.UnForbidden)