获取 .NET 3.5 中 Lambda 表达式中使用的属性名称
我有一个问题已经困扰我一段时间了,但我找不到答案。
我需要获取 Lambda 表达式中引用的属性的名称。我将向返回字符串的方法提供 lambda 表达式。例如,如果我有:
x => x.WeirdPropertyName
那么该方法将返回:
"WeirdPropertyName"
我已经读到可以使用表达式树来完成它,但答案却让我困惑。
感谢您的帮助
I have a problem that has been nagging me for some time now and I can't find the answer.
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"
I have read that it can be done with expression trees, but the answer has eluded me.
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
干得好:
Here you go:
我有一个非常全面的答案 在这里。
除了处理像
x => 这样的表达式之外, x.WeirdPropertyName
,它还可以处理“扩展”表达式,例如x =>; x.WeirdMember.WeirdPropertyName
。这是该答案的代码:
I've got a pretty comprehensive answer here.
In addition to dealing with expressions like
x => x.WeirdPropertyName
, it can also deal with "extended" expressions such asx => x.WeirdMember.WeirdPropertyName
.Here's the code from that answer:
我知道获取属性的字符串名称的唯一方法是通过反射。
The only way I know of getting the string name of a property is via reflection.