1:设置自己的自定义属性
public class NameAttribute:Attribute { private string _description; public NameAttribute(string description) { _description = description; } public string Description { get { return _description; } } }
2:设置获取属性或属性名的类
////// 获取自定义属性Name或者属性名称 /// ///类型 public class AttributeHelperwhere T : new() { /// /// 获取枚举类型自定义属性Name /// /// 枚举 ///public string NameFor(object type) { T test = (T)type; FieldInfo fieldInfo = test.GetType().GetField(test.ToString()); object[] attribArray = fieldInfo.GetCustomAttributes(false); //IList list = fieldInfo.GetCustomAttributesData(); string des = (attribArray[0] as NameAttribute).Description; return des; } /// /// 获取属性自定义属性Name /// /// 表达式 ///public string NameFor(Expression > expr) { string name = PropertyNameFor(expr); T et = new T(); Type type = et.GetType(); PropertyInfo[] properties = type.GetProperties(); object[] attributes = null; foreach (PropertyInfo p in properties) { if (p.Name == name) { attributes = p.GetCustomAttributes(typeof(NameAttribute), true); break; } }//出自 尊重作者辛苦劳动成果,转载请注明出处,谢谢! string des = ((NameAttribute)attributes[0]).Description; return des; } /// /// 获取属性的名称 /// /// ///public string PropertyNameFor(Expression > expr) { var rtn = ""; if (expr.Body is UnaryExpression) { rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name; }//出自 尊重作者辛苦劳动成果,转载请注明出处,谢谢! else if (expr.Body is MemberExpression) { rtn = ((MemberExpression)expr.Body).Member.Name; } else if (expr.Body is ParameterExpression) { rtn = ((ParameterExpression)expr.Body).Type.Name; } return rtn; } }
3:设置测试实体类和枚举
public class MyEntity { public MyEntity() { Name = "Jude"; Age = 11; } [Name("姓名")] public string Name { get; set; } [Name("年龄")] public int Age { get; set; } }
public enum MyEnum { [Name("欧洲")] Europe = 0, [Name("亚洲")] Asia = 1, [Name("美洲")] America = 2 }
4:开始测试
public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { AttributeHelpermyEntityAttr = new AttributeHelper (); MyEntity myEntity = new MyEntity(); AttributeHelper myEnumAttr = new AttributeHelper (); Response.Write(myEntityAttr.NameFor(it => it.Name) + ":" + myEntity.Name + "\n");//姓名:Jude Response.Write(myEntityAttr.NameFor(it => it.Age) + ":" + myEntity.Age + "\n");//年龄:11 Response.Write(myEntityAttr.PropertyNameFor(it => it.Name) + ":" + myEntity.Name + "\n");//Name:Jude Response.Write(myEntityAttr.PropertyNameFor(it => it.Age) + ":" + myEntity.Age + "\n");//Age:11 //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢! Response.Write(myEnumAttr.NameFor(MyEnum.America) + ":" + MyEnum.America + "\n");//美洲:America Response.Write(myEnumAttr.NameFor(MyEnum.Asia) + ":" + MyEnum.Asia + "\n");//亚洲:Asia Response.Write(myEnumAttr.NameFor(MyEnum.Europe) + ":" + MyEnum.Europe + "\n");//欧洲:Europe } }