获取属性名称的扩展方法

我有一个扩展方法来获取属性名称

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

我称之为

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

这工作正常,并将PublishDateTime作为字符串返回给我。

但是我对调用语句有一个问题,它看起来太复杂了,我想要这样的东西。

 this.PublishDateTime.Name() 

有人可以修改我的扩展方法吗?

试试这个:

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

用法是:

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

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

 nameof(PublishDateTime) 

你不能这样做this.PublishDateTime.Name() ,因为唯一会传递给扩展方法的是调用扩展方法的值或引用。

无论是属性,字段,局部变量还是方法结果无关紧要,它都没有可以在扩展方法中访问的名称。

表达式将是“详细的”,请参阅如何将此方法作为扩展方法添加到我的类的属性中? (感谢@ Black0ut )把它放在一个静态助手类中。