首先定义下面的方法:
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=="测试 ");
}
}