How do I call myself through the delegate generated by the expression tree?

Viewed 142

Now I'm going to compile the expression tree into a delegate to generate code dynamically, but I have a problem. I have to call a method in the expression tree, which is exactly the expression tree delegate that has not been dynamically compiled yet. What should I do?

I want to generate the following code from the expression tree:

int i = 0;
Action ac = null;

ac = () =>
{
    //if (i-- > 0)  condition
        ac();
};

The following code does not work and will prompt ac is null

static Action ac = Build();
static Action Build()
{
    return Expression.Lambda<Action>(
        Expression.Call(
            Expression.Constant(ac), //throw ac is null
            typeof(Action).GetType().GetMethod("Invoke")
        )
    ).Compile();
}
1 Answers

Problem with expressions is that you can only pass variable by value, so you need some trick to pass reference. You can do this:

Action<Node> ac = null;
Func<Action<Node>> getAction = () => ac;

And build expression like that:

ac = () =>
{
    //if (i-- > 0)  condition
        getAction()();
};

Another option is to wrap action in some object:

Wrapper<Action> = new Wrapper();
ac = () =>
{
    //if (i-- > 0)  condition
        wrapper.Value();
};
wrapper.Value = ac;

Here is example code:

    class Wrapper<T>
    {
        public T Value { get; set; }
    }

    static void Main(string[] args)
    {
        Node root = new Node
        {
            Name = "First",
            Next = new Node {Name = "Second"}
        };

        var method = Build();
        method(root);
    }

    class Node
    {
        public string Name { get; set; }
        public Node Next { get; set; }
    }

    static Action<Node> Build()
    {
        var wrapper = new Wrapper<Action<Node>>();
        var param = Expression.Parameter(typeof(Node), "node");
        var expr = Expression.Lambda<Action<Node>>(
            Expression.Block(
                // Console.WriteLine("Node name: {0}", node.Name);
                Expression.Call(
                    typeof(Console), 
                    "WriteLine", 
                    Type.EmptyTypes, 
                    Expression.Constant("Node name: {0}"), 
                    Expression.Property(param, "Name")
                ),
                // if (node.Next != null) wrapper.Value(node.Next)
                Expression.IfThen(
                    Expression.ReferenceNotEqual(Expression.Property(param, "Next"), Expression.Constant(null)),
                    // wrapper.Value(node.Next)
                    Expression.Invoke(
                        // wrapper.Value
                        Expression.Property(Expression.Constant(wrapper), "Value"),
                        // node.Next
                        Expression.Property(param, "Next")
                    )
                )
            ),
            param
        );

        return wrapper.Value = expr.Compile();
    }
Related