使用编译表达式调用参数化构造函数

Awk*_*der 3 .net c# reflection expression-trees

我正在尝试创建一个编译的表达式委托来调用一个构造函数接受一个参数,我收到以下异常:

Additional information: variable 'value' of type 'MyType' referenced from scope '', but it is not defined
Run Code Online (Sandbox Code Playgroud)

代码如下:

var constructorInfo = instanceType.GetConstructors().Skip(1).First();

ParameterExpression param = Expression.Parameter(genericArgument, "value");
Delegate constructorDelegate = Expression.Lambda(Expression.New(constructorInfo, new Expression[] { param })).Compile();
Run Code Online (Sandbox Code Playgroud)

我相信我正在接受异常,因为参数'value'没有限定在Expression.Block中.

如何在Expression.Block中调整参数和构造函数表达式的范围?

Mar*_*kus 7

为了声明参数value,您还需要在创建Lambda表达式时指定它(请参阅Expression.Lambda方法的此重载).到目前为止,您只创建一个参数化的lambda表达式,但不声明表达式中使用的参数.更改代码应解决问题:

var lambdaExpr = Expression.Lambda(Expression.New(constructorInfo, 
                                                  new Expression[] { param }), 
                                   param);
Delegate constructorDelegate = lambdaExpr.Compile();
Run Code Online (Sandbox Code Playgroud)