我想这样做:
Console.WriteLine( PrintMyName(x => x.EmailAddress) );
public class User{
public string EmailAddress{get;set;}
}
现在的问题是,propertyInfo
null
是public string PrintMyName(Func<T,object> member){
var propertyInfo = (member.Body as MemberExpression).Member as PropertyInfo;
return propertyInfo.Name;
}
。
{{1}}
这样做的正确方法是什么? 感谢
答案 0 :(得分:0)
应该是这样的:
public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
var body = expression.Body as MemberExpression;
if (body == null)
{
body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
if (body != null)
{
return body.Member.Name;
}
return null;
}
用法(以元组为例):
var theName = GetPropertyName<Tuple<string>>(x => x.Item1);