开发者

Saving a DynamicMethod to disk

开发者 https://www.devze.com 2023-03-13 04:24 出处:网络
I have inherited code that uses DynamicMethod to generate methods at runtime. I also need to modify some of the code that is being generated.

I have inherited code that uses DynamicMethod to generate methods at runtime. I also need to modify some of the code that is being generated.

Since I am a n00b at MSIL, I would love to be able to load the generated code up in Reflector and ensure that the code does what I pray that it does ;)

Only, I can't figure out how to serialize the "Anonymously Host开发者_StackOverflowed DynamicMethods Assembly" to disk. Is this possible? If so, how?


Try this,

  var assemblyName = new AssemblyName("SomeName");
  var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"c:");
  var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name +  ".dll");

  TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
  var methodBuilder = builder.DefineMethod("DynamicCreate", MethodAttributes.Public, typeof(T), new[] { typeof(IDataRecord) }); 
  /* this line is a replacement for your  new DynamicMethod(....)  line of code

  /* GENERATE YOUR IL CODE HERE */

  var t = builder.CreateType();
  assemblyBuilder.Save(assemblyName.Name + ".dll");


I think that if you want to load the method in Reflector or dotPeek, you need to create an actual assembly. To do this, use MethodBuilder instead of DynamicMethod. Most of the usage of them should be the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号