加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:00:23 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个编译的表达式委托来调用一个构造函数接受一个参数,我收到以下异常: Additional information: variable 'value' of type 'MyType' referenced from scope '',but it is not defined 代码如下: var constructorInfo = instanceType.GetCon
我正在尝试创建一个编译的表达式委托来调用一个构造函数接受一个参数,我收到以下异常:

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方法的此 overload).到目前为止,您只创建一个参数化的lambda表达式,但不声明表达式中使用的参数.更改代码应解决问题:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读