c# - 如何使用表达式树调用带有引用变量的方法

标签 c# .net expression-trees

我正在尝试弄清楚如何创建调用具有引用参数的方法的表达式。

让我用一个简单(但人为)的例子来解释我的问题。考虑方法:

    public static int TwiceTheInput(int x)
    {
        return x*2;
    }

我可以创建一个表达式来调用上面的方法,方法如下:

    {
        var inputVar = Expression.Variable(typeof (int), "input");
        var blockExp =
            Expression.Block(
                    new[] {inputVar}
                    , Expression.Assign(inputVar, Expression.Constant(10))
                    , Expression.Assign(inputVar, Expression.Call(GetType().GetMethod("TwiceTheInput", new[] { typeof(int) }), inputVar))
                    , inputVar
                    );
        var result = Expression.Lambda<Func<int>>(blockExp).Compile()();
    }

在执行时,上面的“结果”应该以 20 的值结束。 现在考虑使用引用参数的 TwiceTheInput() 版本:

    public static void TwiceTheInputByRef(ref int x)
    {
        x = x * 2;
    }

如何编写类似的表达式树来调用 TwiceTheInputByRef() 并通过引用传递参数?

解决方案:(感谢 Cicada)。使用:

Type.MakeByRefType()

这是生成表达式树的代码段:

        {
        var inputVar = Expression.Variable(typeof(int), "input");
        var blockExp =
            Expression.Block(
                    new[] { inputVar }
                    , Expression.Assign(inputVar, Expression.Constant(10))
                    , Expression.Call(GetType().GetMethod("TwiceTheInputByRef", new[] { typeof(int).MakeByRefType() }), inputVar)
                    , inputVar
                    );
        var result = Expression.Lambda<Func<int>>(blockExp).Compile()();
    }

最佳答案

你不需要做太多改变,只需删除 Assign 并将 typeof(int) 更改为 typeof(int).MakeByRefType().

var blockExp = Expression.Block(
    new[] { inputVar }
    , Expression.Assign(inputVar, Expression.Constant(10))
    , Expression.Call(
       typeof(Program).GetMethod( 
           "TwiceTheInputByRef", new [] { typeof(int).MakeByRefType() }),
       inputVar)
    , inputVar
);

关于c# - 如何使用表达式树调用带有引用变量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14940171/

相关文章:

c# - MVC Controller if/else 语句

c# - .net core 2.2 和开放的 CORS

c# - 组合多个谓词

.net - ASP.NET 验证码实现

c# - 将表单数据 NameValueCollection 转换为对象

.net - 需要带有 <supportedRuntime/> 的 .NET 4.0 完整配置文件

c# - 表达式树中的动态方法调用

c# - 如何使用 Linq 将 order(autoIncrement) 属性添加到集合?

c# - 如何在运行时才知道类型时创建 Expression.Lambda?

c# - .NET Core 和 .NET Framework 之间 Expression.Subtract for DateTime 的差异