C#成员参数作为表达式并提取字符串名称

时间:2013-09-06 08:37:08

标签: c# expression func

我想这样做:

Console.WriteLine( PrintMyName(x => x.EmailAddress) );


public class User{
   public string EmailAddress{get;set;}
}

现在的问题是,propertyInfo nullpublic string PrintMyName(Func<T,object> member){ var propertyInfo = (member.Body as MemberExpression).Member as PropertyInfo; return propertyInfo.Name; }

{{1}}

这样做的正确方法是什么? 感谢

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);