Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用编译表达式调用参数化构造函数_C#_.net_Reflection_Expression Trees - Fatal编程技术网

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

C# 使用编译表达式调用参数化构造函数,c#,.net,reflection,expression-trees,C#,.net,Reflection,Expression Trees,我正在尝试创建一个已编译的表达式委托来调用使用单个参数的构造函数,我收到以下异常: Additional information: variable 'value' of type 'MyType' referenced from scope '', but it is not defined 代码如下: var constructorInfo = instanceType.GetConstructors().Skip(1).First(); ParameterExpression para

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

Additional information: variable 'value' of type 'MyType' referenced from scope '', but it is not defined
代码如下:

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

ParameterExpression param = Expression.Parameter(genericArgument, "value");
Delegate constructorDelegate = Expression.Lambda(Expression.New(constructorInfo, new Expression[] { param })).Compile();
我相信我收到了异常,因为参数“value”的作用域不在Expression.Block中


如何在Expression.Block中定义参数和构造函数表达式的作用域?

为了声明参数
,您还需要在创建Lambda表达式时指定它(请参见Expression.Lambda方法的此部分)。到目前为止,只创建参数化的lambda表达式,而不声明表达式中使用的参数。更改代码可以解决以下问题:

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

你能用ctor发布类型定义吗?这不太有效,我已经发布了答案below@AwkwardCoder:很高兴听到它现在能工作了。然而,我看不出我的答案有什么不同。相关的更改似乎是将
param
添加到
Expression.Lambda
的调用中作为额外参数。不管怎样,如果它有效,它也有效。@AwkwardCoder:谢谢你的双重检查-我真的不理解这种差异,因为我以前也检查过我的解决方案,无法识别相关的差异。祝你有美好的一天!