有人可以向我解释为什么我似乎无法从 AppDomain.Assembly 加载事件内部抛出异常吗?例如:
class Program
{
static Program()
{
AppDomain.CurrentDomain.UnhandledException += (s, a) =>
{
Console.WriteLine("Caught exception!");
};
AppDomain.CurrentDomain.AssemblyLoad += (s, a) =>
{
Console.WriteLine(string.Format("Assembly {0} loaded", a.LoadedAssembly.FullName));
throw new Exception();
Console.WriteLine("Should never get here...");
};
}
static void Main(string[] args)
{
Console.WriteLine(new ClassLibrary1.Class1().TestString());
Console.WriteLine();
Console.WriteLine("Done...");
Console.ReadLine();
}
}
当我执行此操作时,输出如下:
Assembly ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null loaded
TestString
Done...
谁能向我解释这种行为?谢谢。
EDIT澄清一些事情:
发生这种情况是由于 JIT 编译器的工作方式造成的。它需要先生成 Main() 方法的代码,然后才能开始运行。由于您引用的是 ClassLibrary1.Class1() 类型,因此它需要加载该程序集以检索类型信息。这需要它加载程序集before你的代码开始运行。像这样更改它以获得异常:
using System.Runtime.CompilerServices;
...
static void Main(string[] args) {
Test();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test() {
Console.WriteLine(new ClassLibrary1.Class1().TestString());
Console.WriteLine();
Console.WriteLine("Done...");
Console.ReadLine();
}
现在,静态构造函数可以先运行并在加载 ClassLibrary1 程序集之前注册 AssemblyLoad 事件处理程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)