C#:从 lambda 表达式获取链中的属性名称
我正在开发一个使用 lambda 表达式来指定属性的 API。我正在使用这段与此类似的著名代码(这是简化且不完整的,只是为了弄清楚我在说什么):
public void Foo<T, P>(Expression<Func<T, P>> action)
{
var expression = (MemberExpression)action.Body;
string propertyName = expression.Member.Name;
// ...
}
像这样调用:
Foo((String x) => x.Length);
现在我想通过链接属性来指定属性路径名称,如下所示:
Foo((MyClass x) => x.Name.Length);
Foo 应该能够将路径拆分为其属性名称("Name"
和 "Length"
)。有没有办法通过合理的努力来做到这一点?
有一个看起来类似的问题,但我认为他们正在尝试结合那里有 lambda 表达式。
另一个问题也正在处理嵌套属性名称,但我不太明白他们在说什么。
I'm developing a API that uses lambda expressions to specify properties. I'm using this famous piece of code similar to this one (this is simplified and incomplete, just to make clear what I'm talking about):
public void Foo<T, P>(Expression<Func<T, P>> action)
{
var expression = (MemberExpression)action.Body;
string propertyName = expression.Member.Name;
// ...
}
To be called like this:
Foo((String x) => x.Length);
Now I would like to specify a property path by chaining property names, like this:
Foo((MyClass x) => x.Name.Length);
Foo should be able to split the path into its property names ("Name"
and "Length"
). Is there a way to do this with reasonable effort?
There is a somehow similar looking question, but I think they are trying to combine lambda expressions there.
Another question also is dealing with nested property names, but I don't really understand what they are talking about.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样的东西吗?
Something like this?
我玩了一下 ExpressionVisitor :
用法:
I played a little with ExpressionVisitor:
Usage:
老问题,我知道......但如果这只是您需要的名称,则更简单的方法是:
编辑:
Old question, I know... but if it's only the names you need, an even simpler way to do it is:
EDIT:
我在客户端和服务器之间有一个共享的 .NET 标准 DTO,表达式是创建可以在 Api 端重建和执行的查询字符串的好方法。
通过网络创建类型安全查询的完美方法。
我离题了,我还需要一个属性路径
来生成一个像
我这样的字符串
I have a shared .NET standard DTO between client and server and expressions are a great way to create query strings that can be rebuilt and executed Api side.
A perfect way to create Type safe queries over the wire.
I digress, I needed a property path also
To produce a string like
I went with this
我重构了这些答案以使用递归,因此不需要反转顺序。我只需要属性树,因此省略了除 MemberExpressions 之外的所有内容。如果需要的话,添加功能应该很简单。
I refactored these answers to use recursion, so no need for order reversal. I only need the property tree, so left out all but MemberExpressions. Should be simple to add functionality if need be.