Jef*_*eff 6 linq expression-trees expressionvisitor c#-4.0
在有人喊出答案之前,请先阅读问题.
.NET 4.0的ExpressionVisitor中该方法的目的是什么:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
Run Code Online (Sandbox Code Playgroud)
我对该方法的目的的第一个猜测是,它将访问nodes参数指定的每个树中的每个节点,并使用elementVisitor函数的结果重写树.
情况似乎并非如此.实际上这种方法似乎比什么都没有,除非我在这里遗漏了一些东西,我强烈怀疑我是......
我尝试在我的代码中使用此方法,当事情没有按预期工作时,我反映了方法并发现:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
{
T[] list = null;
int index = 0;
int count = nodes.Count;
while (index < count)
{
T objA = elementVisitor(nodes[index]);
if (list != null)
{
list[index] = objA;
}
else if (!object.ReferenceEquals(objA, nodes[index]))
{
list = new T[count];
for (int i = 0; i < index; i++)
{
list[i] = nodes[i];
}
list[index] = objA;
}
index++;
}
if (list == null)
{
return nodes;
}
return new TrueReadOnlyCollection<T>(list);
}
Run Code Online (Sandbox Code Playgroud)
那么有人会在哪里使用这种方法呢?我在这里错过了什么?
谢谢.
在我看来,这是一种将任意变换函数应用于表达式树的便捷方法,并返回转换后的结果树,如果没有变化,则返回原始树。
我看不出这与标准表达式访问者的模式有何不同,除了使用访问者类型之外,它使用函数。
至于用法:
Expression<Func<int, int, int>> addLambdaExpression= (a, b) => a + b;
// Change add to subtract
Func<Expression, Expression> changeToSubtract = e =>
{
if (e is BinaryExpression)
{
return Expression.Subtract((e as BinaryExpression).Left,
(e as BinaryExpression).Right);
}
else
{
return e;
}
};
var nodes = new Expression[] { addLambdaExpression.Body }.ToList().AsReadOnly();
var subtractExpression = ExpressionVisitor.Visit(nodes, changeToSubtract);
Run Code Online (Sandbox Code Playgroud)
您没有解释您期望它的行为方式以及为什么您认为它几乎没有任何作用。
| 归档时间: |
|
| 查看次数: |
3723 次 |
| 最近记录: |