简体   繁体   English

Expression.Lamda无法使用动态生成的类

[英]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). 然后,我们可以在表达式中使用字段(因为已经建立了基本类型)。

  • Then we use Emit to create pass-params constructors ( here is an example) 然后我们使用Emit创建pass-params构造函数( 是一个示例)
  • Finally, we just change type 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. 最后,我们只是改变类型Tthis参数,在方法T的基本类型(有一个隐式转换的孩子- >基础,所以这是确定),然后我们就可以在我们的生成方法使用的字段。

Here is a complete code (see ServiceClient , Helpers.XLambdaExpression , Helper.EmitHelper ). 是完整的代码(请参阅ServiceClientHelpers.XLambdaExpressionHelper.EmitHelper )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM