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

Expression.New(..) - but I already have an object

正在查看 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 的新实例 - 我已经有一个实例,我只想调用它的一个方法。

代码基本上是这样做的:

new SampleClass().AddIntegers(1, 2)

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

sampleClassInstance.AddIntegers(1, 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)
    );