使用表达式树,获取类的属性说明

来源:互联网 发布:软件源代码怎么找 编辑:程序博客网 时间:2024/06/16 15:08

首先定义下面的方法:

string GetDescription<T,F>(Expression<Func<T,F>> property){    var att =  GetDescriptionAttrbute(property);    return att.Description;}        private 【DescriptionAttrbute】 GetDescriptionAttrbute(Expression<Func<T, object>> property)        {            if (property== null) return null;            var body = property.Body as MemberExpression;            if (body == null)            {                var temp = property.Body as UnaryExpression;                if (temp != null)                {                    body = temp.Operand as MemberExpression;                }            }            if (body == null)            {                throw new System.Exception(string.Format("Error Expression:{0}!", property));            }            return body.Member.GetCustomAttributes(typeof(DescriptionAttrbute),true) as DescriptionAttrbute;        }


然后这样使用:

public class Test{  [Description("测试")]  public string Key="123";}public class AttributeHelperTest{   public static void Test()   {      Test test=new global::Test.Test();      string content=AtttributeHelper.GetDestcripiton<Test>(info=>info.Key);      Console.Write(content=="测试 ");   }}


 

 

原创粉丝点击