Extension method to get property name

喜夏-厌秋 提交于 2019-12-17 20:51:20

问题


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?


回答1:


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



回答2:


With C# 6.0, you can use:

nameof(PublishDateTime)



回答3:


You can't do this.PublishDateTime.Name(), as the only thing that will be passed into the extension method is the value or reference on which you call the extension method.

Whether it's a property, field, local variable or method result doesn't matter, it won't have a name that you can access inside the extension method.

The expression will be "verbose", see How can I add this method as an extension method to properties of my class? (thanks @Black0ut) to put it in a static helper class.



来源:https://stackoverflow.com/questions/32376472/extension-method-to-get-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!