为调用方法C#提供的参数数量不正确

时间:2019-01-25 19:17:12

标签: c# dynamic reflection expression adapter

我有一个采用2个参数的方法。我想在运行时构建一个方法,该方法将调用此方法并默认传递一个参数。另一个参数将在新函数中传递。

我试图创建调用此方法的lambda表达式,但出现错误:为调用方法提供的参数数量不正确。

static class Program
{
    static void Main(string[] args)
    {
        var method = typeof(Program).GetMethod("Method");
        // here i want to set first parameter as "parameter1" when new method will be called
        var lambda = Expression.Lambda<Func<string, string>>(Expression.Call(method, Expression.Constant("parameter1")));
        var adapter = lambda.Compile();
        // and here i wanna pass only one agrument - second (parameter2)
        var result = adapter("parameter2");

        // expected result "parameter1 ---- parameter2"
    }

    public static string Method(string parameter1, string parameter2)
    {
        return $"{parameter1} ---- {parameter2}";
    }

我只想在调用函数时传递第二个参数。首先必须自动指定。

1 个答案:

答案 0 :(得分:2)

您已定义了常量,但还需要定义另一个参数,以便可以将其赋予var method = typeof(Program).GetMethod("Method"); // here i want to set first parameter as "parameter1" when new method will be called var param = Expression.Parameter(typeof(string)); var call = Expression.Call(method, Expression.Constant("parameter1"), param); var lambda = Expression.Lambda<Func<string, string>>(call, param); var adapter = lambda.Compile(); // and here i wanna pass only one agrument - second (parameter2) var result = adapter("parameter2");

Func<string, string> adapter = p => Method("parameter1", p);

当然,我将假设您有一个真正的动态用例。否则,您可以这样写:

{{1}}