您的位置:首页 > 编程语言 > C#

C#给枚举增加一个Attribute,并通过反射获取Attribute的值。(借鉴)

2013-09-30 13:54 393 查看
[AttributeUsage(AttributeTargets.Field)]
public class EnumExtension : Attribute
{
private string title;
public EnumExtension(string title)
{
this.title = title;
}
public static string Get(Type tp, string name)
{
MemberInfo[] mi = tp.GetMember(name);
if (mi != null && mi.Length > 0)
{
EnumExtension attr = Attribute.GetCustomAttribute(mi[0], typeof(EnumExtension)) as EnumExtension;
if (attr != null)
{
return attr.title;
}
}
return null;
}
public static string Get(object enm)
{
if (enm != null)
{
MemberInfo[] mi = enm.GetType().GetMember(enm.ToString());
if (mi != null && mi.Length > 0)
{
EnumExtension attr = Attribute.GetCustomAttribute(mi[0], typeof(EnumExtension)) as EnumExtension;
if (attr != null)
{
return attr.title;
}
}
}
return null;
}
}
public enum BorderStyle
{
[EnumExtension("正常")]
None,
[EnumExtension("圆角")]
Rounded
}


使用以下的方法就能取得枚举的Attribute值:

string name = EnumExtension.Get(BorderStyle.Rounded);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: