Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an extension method to get property name as

public static string Name<T>(this Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

I am calling it as

string Name = ((Expression<Func<DateTime>>)(() => this.PublishDateTime)).Name();

This is working fine and returns me PublishDateTime as string.

However I have an issue with the calling statement, it is looking too complex and I want some thing like this.

this.PublishDateTime.Name()

Can some one modify my extension method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

public static string Name<T,TProp>(this T o, Expression<Func<T,TProp>> propertySelector)
{
    MemberExpression body = (MemberExpression)propertySelector.Body;
    return body.Member.Name;
}

The usage is:

this.Name(x=>x.PublishDateTime);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...