Extension method to get property name

后端 未结 3 1794
走了就别回头了
走了就别回头了 2020-12-11 06:42

I have an extension method to get property name as

public static string Name(this Expression> expression)
{
    MemberExpression         


        
相关标签:
3条回答
  • 2020-12-11 07:25

    With C# 6.0, you can use:

    nameof(PublishDateTime)
    
    0 讨论(0)
  • 2020-12-11 07:38

    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);
    
    0 讨论(0)
  • 2020-12-11 07:38

    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.

    0 讨论(0)
提交回复
热议问题