0

我想做这个:

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

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

4

1 回答 1

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

用法(以 Tuple 为例):

var theName = GetPropertyName<Tuple<string>>(x => x.Item1);
于 2013-09-06T08:45:59.337 回答