简体   繁体   中英

C# member parameter as expression and extract the string name

I want to do this:

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


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

Now the problem is, as seen bellow that propertyInfo is null .

public string PrintMyName(Func<T,object> member){
   var propertyInfo = (member.Body as MemberExpression).Member as PropertyInfo;
   return propertyInfo.Name;
}

What is the righte way to do this? Thanks

should be something like this:

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

usage (use Tuple as an example):

var theName = GetPropertyName<Tuple<string>>(x => x.Item1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM