将节点/属性添加到表达式树 [英] Adding a node/property to an Expression Tree
问题描述
这是我第一次真正处理过表达式树,我有点迷茫.我很抱歉 这个问题根本没有任何意义.请考虑以下类:
This is the first time I've really dealt with Expression Trees, and I am a bit lost. I apologise if this question just doesn't make any sense at all. Consider the following classes:
public class Foo<T> {
public T Value { get; set; }
public bool Update { get; set;}
}
public class Bar {
public Foo<bool> SomeBool { get; set; }
public Foo<string> SomeString { get; set; }
}
所以现在我有一个如下所示的辅助方法:
So right now I have a helper method that looks like this:
public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression, Expression<Func<Bar, T>> valExpression, Expression<Func<Bar, bool>> updateExpression)
{
// Do some stuff with those expressions.
}
然后像这样被调用:
Helper(b=>b.SomeBool,b=>b.SomeBool.Value,b=>b.SomeBool.Update);
但是我不喜欢构建三个几乎完全相同的表达式,并且必须显式地传递 他们进入助手.我更喜欢这样的东西:
But I dislike building three almost exact same expressions, and having to explicitly pass them into the Helper. What I would prefer is to something like this:
Helper(b=>b.SomeBool);
然后:
public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression)
{
// Do some stuff
var valExpression = ???; // append `.Value` to baseExpression
var updateExpression = ???; // append `.Update` to baseExpression
}
但是我不太确定该怎么做... 正确的方向会被错误地应用.
But I'm not really sure how to do that... Its boggling my mind, any shove in the right direction would be wildly appriciated.
推荐答案
可以;如果您有baseExpression
,则类似于:
Sure; if you have baseExpression
, then something like:
var valExpression = Expression.Lambda<Func<Bar, T>>(
Expression.PropertyOrField(baseExpression.Body, "Value"),
baseExpression.Parameters);
var updateExpression = Expression.Lambda<Func<Bar, bool>>(
Expression.PropertyOrField(baseExpression.Body, "Update"),
baseExpression.Parameters);
这篇关于将节点/属性添加到表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!