麻烦" Assembly.EntryPoint.Invoke" [C#]

时间:2015-02-19 20:37:43

标签: c# reflection compilation runtime .net-assembly

我有以下问题:
我正在使用CSharpCodeProvider中的Microsoft.CSharp在运行时编译C#代码。如果我双击生成的文件,创建的应用程序将完美运行。

但是,如果我使用Assembly.Load加载我创建的程序集并使用Assembly.Load("...").EntryPoint.Invoke(null, null)调用entrypoint-method,则会得到 NullReferenceException

<小时/> NullReferenceException 指的是.EntryPoint - 属性的值。
当我调试包含加载的Assembly的变量时,VisualStudio显示以下内容:

Error
Larger image

错误是德语,意思是“local”或参数“asm”的值在此指令指针中不可用,因此无法确定。它可能在优化期间被删除。

<小时/> 我想在此处添加我生成的程序集优化(我还添加了编译器参数/optimize-,这会阻止优化。)
我通过尝试此代码执行了另一项测试来确定错误来源:

Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);

asm.EntryPoint.Invoke(null, argv);

此代码还在包含Invoke - 调用的行中抛出 NullReferenceException

<小时/> 有人在这里知道,这个错误来自哪里,我可以解决它?
非常感谢你 :)


编辑:

entrypoint-method定义如下:

namespace tmp
{
   public static class Program
   {
      [STAThread]
      public static void Main(string[] argv)
      { ... }
   }
}

我也尝试用.EntryPoint.Invoke(null, new string[]{"test", "argument"})调用它,但它没有解决问题:/

编辑#2:我发现了我的错误 - 请查看来自@Hans Passant和我自己的评论

〜关闭〜

2 个答案:

答案 0 :(得分:2)

Hans Passant's comment复制并粘贴:

// Get your assembly.
Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);

// Get your point of entry.
MethodInfo entryPoint = asm.EntryPoint;

// Invoke point of entry with arguments.
entryPoint.Invoke(null, new object[] { new string[] { "arg1", "arg2", "etc" } } );

如果要从嵌入式资源访问程序集,请使用以下代码段:

byte[] yourResource = Properties.Resources.YourResourceName;

Assembly asm = Assembly.Load(yourResource);

答案 1 :(得分:0)

如果你尝试这样的东西会怎么样?

Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);
MethodInfo myMethod = asm.EntryPoint;
myMethod.Invoke(null, args); 

假设您知道要调用的方法