调用静态方法抛出TargetException, HResult -2146232829
本文关键字:HResult -2146232829 TargetException 静态方法 调用 | 更新日期: 2023-09-27 18:14:27
下面的调用将产生一个
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
的呼吁似乎是正确的。有什么问题吗?
var builderAssembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save, directory.FullName);
只允许程序集保存,而不允许运行。参见AssemblyBuilderAccess文档。
在您的情况下,您应该使用AssemblyBuilderAccess.RunAndSave