How do I call a method using a LINQ expression?

c# dynamic-language-runtime expression-trees linq

Question

I've been playing around with the DLR a bit and am a bit stuck on calling methods. For example, suppose I want to make an expression to push something onto a stack:

class StackInfo{

    protected Stack<SomeClass> _stack;

    public Expression Push(SomeClass item)
    {
        MethodInfo mi = _stack.GetType().GetMethod("Push");
        return Expression.Call(_stack, mi, item);
    }
}

I'm getting stuck because I'm not really sure how to get an Expression out of _stack or item. Could somebody push me in the right direction?

1
2
5/26/2009 11:44:23 PM

Accepted Answer

Use the Expression.Constant factory method:

class StackInfo
{
    protected Stack<SomeClass> _stack;

    public Expression Push(SomeClass item)
    {
        MethodInfo mi = _stack.GetType().GetMethod("Push");

        return Expression.Call(Expression.Constant(_stack), mi, Expression.Constant(item));
    }
}
3
5/27/2009 12:27:25 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow