遍历Linq表达式以设置属性字段的值 [英] Traverse a Linq Expression to set the value of a property field

查看:285
本文介绍了遍历Linq表达式以设置属性字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管看起来很简单,但这是一个非常复杂的问题.我认为除非有人知道更好的方法,否则我将不得不遍历整个表达式树.

This is a very complicated question even though it looks simple. I think I would have to traverse the entire expression tree unless someone knows a better way.

假设我有一个用户对象

class User
{
    public UserAccount Account {get;set;}
}
class UserAccount
{
    public Name {get;set;}
}
var user = new User() { Account = new UserAccount()};

如何使用linq表达式设置Name的属性

How could I use linq expressions to set the property of Name

SetValue(c => c.Account.Name, "Test");

推荐答案

嗯,您不仅要遍历表达式树:还必须将遇到的最终属性"getter"转换为"setter属性" ".本质上,您希望找到充当getter的目标"的表达式(即要获取其属性的对象),对其求值以获取目标,然后为最终属性找到相应的setter,并用目标和新值来调用它.

Well, you'd not only have to traverse the expression tree: you'd also have to convert final property "getter" you encounter into a property "setter". Essentially you'd want to find the expression which acts as the "target" of the getter (i.e. the object it's going to get the property of), evaluate it to get the target, then find the corresponding setter for the final property, and call it with the target and the new value.

请注意,仅通过使用表达式树来表示"getter",您就失去了一些期望的编译时安全性……因为调用者可以传入只读属性:

Note that by only requiring the expression tree to represent the "getter", you're losing some of the compile-time safety you might expect... because a caller could pass in a read-only property:

SetValue(c => c.Account.Name.Length, 0); // string.Length is read-only

另一种替代方法是更改​​代码,以使lambda表达式代替设置器:

Another alternative would be to change your code to make the lambda expression represent the setter instead:

SetValue((c, value) => c.Account.Name = value, "Test");

然后,您甚至不需要表达式树-您可以使用一个简单的委托,并适当地执行它.

Then you wouldn't even need an expression tree - you could use a simple delegate, and just execute it appropriately.

不幸的是,您还没有真正向我们提供足够的信息来了解您要达到的目标,以了解这是否是可行的建议.

Unfortunately you haven't really given us enough information about what you're trying to achieve to know whether this is a feasible suggestion.

这篇关于遍历Linq表达式以设置属性字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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