获取属性名称的扩展方法 [英] Extension method to get property name

查看:128
本文介绍了获取属性名称的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我称它为

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

这工作正常,并以字符串形式返回我PublishDateTime.

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?

推荐答案

尝试一下:

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

用法是:

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

这篇关于获取属性名称的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆