Expression.New(..) - 但我已经有了一个对象

时间:2015-10-28 22:22:52

标签: c# expression-trees

查看C#中的表达式树,并且正在阅读this article

// Add the following directive to your file:
// using System.Linq.Expressions;  
public class SampleClass
{
    public int AddIntegers(int arg1, int arg2)
    {
        return arg1 + arg2;
    }
}

static public void TestCall()
{
    // This expression represents a call to an instance method that has two arguments.
    // The first argument is an expression that creates a new object of the specified type.
    Expression callExpr = Expression.Call(
        Expression.New(typeof(SampleClass)),
        typeof(SampleClass).GetMethod("AddIntegers", new Type[] { typeof(int), typeof(int) }),
        Expression.Constant(1),
        Expression.Constant(2)
        );

    // Print out the expression.
    Console.WriteLine(callExpr.ToString());

    // The following statement first creates an expression tree,
    // then compiles it, and then executes it.
    Console.WriteLine(Expression.Lambda<Func<int>>(callExpr).Compile()());

    // This code example produces the following output:
    //
    // new SampleClass().AddIntegers(1, 2)
    // 3
}

我想做一些与此几乎完全相同的事情,除了我不想创建SampleClass的新实例 - 我已经有了一个实例,我只想在其上调用一个方法。 / p>

代码基本上是这样做的:

new SampleClass().AddIntegers(1, 2)

...使用表达式树;但是,我想这样做:

sampleClassInstance.AddIntegers(1, 2)

这是我可以做的事情,还是我应该坚持反思呢?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

public class SampleClass
{
    public int AddIntegers(int a, int b)
    {
        return a + b;
    }
}

var sampleClass = new SampleClass();
Expression callExpr = Expression.Call(
    Expression.Constant(sampleClass),
    typeof(SampleClass).GetMethod("AddIntegers", new Type[] { typeof(int), typeof(int) }),
    Expression.Constant(1),
    Expression.Constant(2)
    );