以下调用导致
TargetException
HResult = -2146232829
Message = Error in the application.
拨打:
builderType.CreateType();
// Exception on the following line:
int res1 = (int) builderType.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new Object [] { ((object) (new string [] { "Test" })), });
背景:
此调用是在创建TypeBuilder
和MethodBuilder
之后发出的,如下所示:
var domain = AppDomain.CurrentDomain;
var name = new AssemblyName("HouseOfSynergy.PowerTools.ProcessRestarter");
var builderAssembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save, directory.FullName);
var builderModule = builderAssembly.DefineDynamicModule("HouseOfSynergy.PowerTools.ProcessRestarter", "HouseOfSynergy.PowerTools.ProcessRestarter.exe", Global.Instance.Debug);
var builderType = builderModule.DefineType("Program", TypeAttributes.Class | TypeAttributes.Public);
var builderMethod = builderType.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Private, typeof(int), new Type [] { typeof(string []) });
请注意,如果我删除导致错误的Invoke
调用,则动态程序集会加载并正确执行。对Invoke
的呼吁似乎是正确的。对于出了什么问题的任何想法?
答案 0 :(得分:3)
在第
行var builderAssembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save, directory.FullName);
您只允许保存,而不是运行。请参阅AssemblyBuilderAccess documentation。
在您的情况下,您应该使用AssemblyBuilderAccess.RunAndSave
。