使用HResult -2146232829调用抛出TargetException的静态方法

时间:2014-07-24 08:57:49

标签: c# .net reflection invoke reflection.emit

以下调用导致

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

背景:

此调用是在创建TypeBuilderMethodBuilder之后发出的,如下所示:

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的呼吁似乎是正确的。对于出了什么问题的任何想法?

1 个答案:

答案 0 :(得分:3)

在第

var builderAssembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save, directory.FullName);

您只允许保存,而不是运行。请参阅AssemblyBuilderAccess documentation

在您的情况下,您应该使用AssemblyBuilderAccess.RunAndSave