[英]Expression.Lamda is not working with dynamically generated class
Here is sample code do test: 这是做测试的示例代码:
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("asm"), AssemblyBuilderAccess.Run);
var builder = assembly.DefineDynamicModule("MainModule");
Type type = builder.DefineType("newType");
var parameter = Expression.Parameter(type);
Console.WriteLine(type);
var expr = Expression.Lambda(Expression.Constant(1), parameter);
Here I get an exception 在这里我有一个例外
Specified method is not supported 不支持指定的方法
How can I avoid it? 我该如何避免呢? I don't have this type an compile-time, and I want to create a constructor by using Expression
s instead of Emitting it manually. 我没有此类型的编译时,我想通过使用Expression
创建一个构造函数,而不是手动发送它。 Is it even possible? 可能吗? I did it with instance methods, but I did it without using this
. 我使用实例方法来实现,但是我没有使用this
。 Now I need it, but access to type if forbidden while it is under construction. 现在我需要它,但是在构造过程中禁止访问类型。
Well, I found an elegant workaround for this. 好吧,我为此找到了一种优雅的解决方法。
Firstly, we just create a base class, in my case it was: 首先,我们只创建一个基类,在我的例子中是:
public abstract class AsyncClientBase { protected readonly IAsyncRequestProcessor Processor; protected AsyncClientBase(IAsyncRequestProcessor processor) { Processor = processor; } }
Then we can use fields in our expressions (because base type is already builded). 然后,我们可以在表达式中使用字段(因为已经建立了基本类型)。
T
of this
parameter in methods on T
's base type (there is an implicit conversion child -> base, so that's ok), and we are able to use fields in our generated methods. 最后,我们只是改变类型T
的this
参数,在方法T
的基本类型(有一个隐式转换的孩子- >基础,所以这是确定),然后我们就可以在我们的生成方法使用的字段。 Here is a complete code (see ServiceClient
, Helpers.XLambdaExpression
, Helper.EmitHelper
). 这是完整的代码(请参阅ServiceClient
, Helpers.XLambdaExpression
, Helper.EmitHelper
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.