Saving a DynamicMethod to disk

不问归期 提交于 2019-12-01 17:39:36

问题


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 Hosted DynamicMethods Assembly" to disk. Is this possible? If so, how?


回答1:


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.




回答2:


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");


来源:https://stackoverflow.com/questions/6349332/saving-a-dynamicmethod-to-disk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!