7

誰かが答えを叫ぶ前に、質問を読んでください。

.NET4.0のExpressionVisitorのメソッドの目的は何ですか。

public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)

このメソッドの目的についての私の最初の推測は、パラメーターで指定された各ツリーの各ノードにアクセスし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);
}

では、誰かが実際にこの方法をどこで使用するのでしょうか。ここで何が欠けていますか?

ありがとう。

4

1 に答える 1

4

式ツリーに任意の変換関数を適用し、結果の変換されたツリー、または変更がない場合は元のツリーを返す便利なメソッドのように見えます。

これが、ビジタータイプを使用する以外は、関数を使用する標準的な式ビジターのパターンとどのように異なるのかわかりません。

使用法について:

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);

あなたはそれがどのように振る舞うと期待したのか、そしてなぜそれが何もしないと思うのかを説明しません。

于 2010-07-05T17:35:46.460 に答える