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

标签 c# .net reflection expression-trees

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

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 中限定参数和构造函数表达式的范围?

最佳答案

为了声明参数 value,您还需要在创建 Lambda 表达式时指定它(参见 Expression.Lambda 方法的 overload)。到现在为止,您只创建了一个参数化的 lambda 表达式,但没有声明表达式中使用的参数。更改您的代码应该可以解决问题:

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

关于c# - 使用编译表达式调用参数化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22064755/

相关文章:

c# - [param : NotNull] mean in C#? 是什么

C# 将 RichTextBox 中的字符串的一部分加粗

c# - Windows 手机 : date picker and button

java - 使用反射检查方法的返回值是否为 List<String>

c# - 使用反射获取继承接口(interface)的类的属性

c# - 对象上的方法 ToString() 添加反斜杠以转义字符

c# - IDE0057 子串可以简化

.net - Automapper IList-方法实现中主体的签名和声明不匹配

.net - 将 MonoObject 强制转换为 MonoClass(其中方法调用返回类型)

java.lang.ClassCastException : com. sun.proxy.$Proxy47 无法转换为