通过枚举来获取属性,和通过枚举的值来获取属性
public enum TestEmun
{
[Remark("AAA")]
aaa=1,
[Remark("BBB")]
bbb=2,
[Remark("CCC")]
ccc=3
}
public void GetEnumName()
{
//需要引用 Lib.DataModel.SysEnum 命名空间才可以使用 扩展方法
string name = TestEmun.aaa.GetRemark();
Console.WriteLine(name);
/*
name 值为 AAA
*/
}
public void GetName()
{
var name=1.GetEnumRemark(typeof(TestEmun));
Console.WriteLine(name);
}
/// <summary>
/// 备注特性
/// </summary>
public class RemarkAttribute : Attribute
{
private string m_remark;
public RemarkAttribute(string remark)
{
this.m_remark = remark;
}
/// <summary>
/// 备注
/// </summary>
public string Remark
{
get { return m_remark; }
set { m_remark = value; }
}
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="val">枚举值</param>
/// <returns></returns>
public static string GetEnumRemark(Enum val)
{
Type type = val.GetType();
FieldInfo fd = type.GetField(val.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(RemarkAttribute), false);
string name = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
name = attr.Remark;
}
return name;
}
}
/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="em"></param>
/// <returns></returns>
public static string GetRemark(this Enum em)
{
Type type = em.GetType();
FieldInfo fd = type.GetField(em.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(RemarkAttribute), false);
string name = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
name = attr.Remark;
}
return name;
}
/// <summary>
/// 通过枚举值来获取枚举的备注信息
/// </summary>
/// <param name="val"></param>
/// <param name="T"></param>
/// <returns></returns>
public static string GetEnumRemark(this int val,Type T)
{
Type type=T;
string name = Enum.GetName(type, val);
if(name==null)
return string.Empty;
FieldInfo fd=type.GetField(name);
object[] attrs = fd.GetCustomAttributes(typeof(RemarkAttribute), false);
string s = string.Empty;
foreach (RemarkAttribute attr in attrs)
{
s = attr.Remark;
}
return s;
}
}
来源:http://blog.csdn.net/xxj_jing/article/details/8556780