//方法:
public static string GetEnumDescription<TEnum>(object value)
{
Type enumType = typeof(TEnum);
if (!enumType.IsEnum)
{
throw new ArgumentException("enumItem requires a Enum ");
}
var name = Enum.GetName(enumType, Convert.ToInt32(value));
if (name == null)
return string.Empty;
object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
{
return string.Empty;
}
else
{
DescriptionAttribute attr = objs[0] as DescriptionAttribute;
return attr.Description;
}
}
// 调用:
string desc=GetEnumDescription<Filter>(Filter.Public); //得到Filter(enum)中,为Public 所定义的描述信息.
// Filter枚举的描述:
public enum Filter
{
/// <summary>
/// 全部
/// </summary>
[Description("全部")]
All = 1,
/// <summary>
/// 已分配
/// </summary>
[Description("已分配")]
Assigned = 2,
/// <summary>
/// 待分配
/// </summary>
[Description("待分配")]
Assigning = 3,
/// <summary>
/// 返回调整
/// </summary>
[Description("返回调整")]
Adjusting = 4,
/// <summary>
/// 已拒绝
/// </summary>
[Description("已拒绝")]
Reject = 5,
/// <summary>
/// 公共
/// </summary>
[Description("公共")]
Public = 6,
/// <summary>
/// Sales把发回调整的客户编辑后不先提交只保存信息
/// </summary>
[Description("草稿")]
Draft = 7,
/// <summary>
/// 排队
/// </summary>
[Description("排队")]
InQueue = 8,
/// <summary>
/// 发放给大区经理审批
/// </summary>
[Description("审批转移")]
ToManagerCheck = 9,
/// <summary>
/// 不返回任何值的条件
/// </summary>
None = -1,
}
//4, DescriptionAttribute 的定义:
public class DescriptionAttribute : Attribute
{
public DescriptionAttribute(string desc);
public string Description { get; set; }
}
///
public partial class 枚举_Enum_自定义属性 : System.Web.UI.Page
{
protected void Page_Load(object sender , EventArgs e)
{
string desc = GetEnumDescription<MyColorEnum>(MyColorEnum.red);
//desc = GetEnumDescription<MyColorEnum>(1);
Response.Write(desc);
}
public enum MyColorEnum
{
[DescriptionAttribute("红色")]
red ,
[DescriptionAttribute("蓝色")]
blue ,
[DescriptionAttribute("绿色")]
green ,
[DescriptionAttribute("白色")]
white
}
//其实这个属性已经有了:
//public class DescripteAttribute : Attribute
//{
// public DescripteAttribute(string desc)
// {
// this._description = desc;
// }
// private string _description;
// public string Description
// {
// get
// {
// return this._description;
// }
// set
// {
// this._description = value;
// }
// }
//}
/// <summary>
/// 获取枚举项的描述
/// </summary>
/// <param name="enumItem">具体枚举类型</param>
/// <returns></returns>
public static string GetEnumDescription<TEnum>(object value)
{
Type enumType = typeof(TEnum);
if(!enumType.IsEnum)
{
throw new ArgumentException("不是枚举类型");
}
string enumItem = Enum.GetName(enumType , Convert.ToInt32(value));
if(enumItem == null)
{
return string.Empty;
}
object[] objs = enumType.GetField(enumItem).GetCustomAttributes(typeof(DescriptionAttribute) , false);
if(objs == null || objs.Length == 0)
{
return string.Empty;
}
else
{
DescriptionAttribute attr = objs[0] as DescriptionAttribute;
return attr.Description;
}
}
}