简体   繁体   English

获取属性名的扩展方法

[英]Extension method to get property name

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.这工作正常,并将PublishDateTime作为字符串返回。

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?有人可以修改我的扩展方法吗?

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

使用 C# 6.0,您可以使用:

nameof(PublishDateTime)

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.您不能这样做this.PublishDateTime.Name() ,因为将传递给扩展方法的唯一内容是您调用扩展方法的值或引用。

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. (感谢@Black0ut )将其放入静态帮助器类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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