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

本文关键字:一个对象 New Expression | 更新日期: 2023-09-27 18:19:50

查看C#中的表达式树并阅读了这篇文章。

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

这是我能做的事情吗,还是我应该坚持反思?

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

您可以这样做:

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