获取 .NET 3.5 中 Lambda 表达式中使用的属性名称 [英] Get the property name used in a Lambda Expression in .NET 3.5
本文介绍了获取 .NET 3.5 中 Lambda 表达式中使用的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题困扰了我一段时间,但我找不到答案.
I have a problem that has been nagging me for some time now and I can't find the answer.
我需要获取在 Lambda 表达式中引用的属性的名称.我会将 lambda 表达式提供给一个将返回字符串的方法.例如,如果我有:
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
然后该方法将返回:
"WeirdPropertyName"
我已经读到它可以用表达式树来完成,但我没有找到答案.
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;
}
这篇关于获取 .NET 3.5 中 Lambda 表达式中使用的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文