习惯于在一个lambda防爆pression在.NET 3.5的属性名 [英] Get the property name used in a Lambda Expression in .NET 3.5

查看:191
本文介绍了习惯于在一个lambda防爆pression在.NET 3.5的属性名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,一直唠叨我有一段时间了,我无法找到答案。

I have a problem that has been nagging me for some time now and I can't find the answer.

我需要获得一个在一个lambda防爆pression被引用的属性的名称。我将提供拉姆达EX pression到这将返回一个字符串的方法。举例来说,如果我有:

I need to obtain the name of the property that is being referenced in a Lambda Expression. I would provide the lambda expression to a method that would return a string. For example if I have:

x => x.WeirdPropertyName

那么该方法将返回:

then the method would return:

"WeirdPropertyName"

我已阅读,它可以与前pression树木来完成,但得到的答复一直躲避我。

I have read that it can be done with expression trees, but the answer has eluded me.

感谢您的帮助

推荐答案

在这里你去:

string GetPropertyName<T>(Expression<Func<T>> property)
{
    var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
    if (propertyInfo == null)
    {
        throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
    }
    return propertyInfo.Name;
}

这篇关于习惯于在一个lambda防爆pression在.NET 3.5的属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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