【发布时间】:2011-01-25 08:52:50
【问题描述】:
(标题是:“TypeLoadException 并不总是包装到使用反射的 TargetInvocationException”)
通过 BLToolkit,我发现了一个有趣的事实 - methodInfo.Invoke 并不总是在调用方法中捕获异常。
查看示例 - 它在方法的静态构造函数中模拟异常,通过反射调用。
问题是 TestComponent 继承自 Component 并且重写了 Dispose 方法。 因此,在此示例中将有 2 条消息 - 一条“处理”和一条“未处理” - 似乎组件在较低级别的反射内部具有不同的处理方式。
如果我们注释掉方法 Dispose(bool disposing) - 我们将只收到“处理”消息。
谁能解释为什么会发生并提出解决方案? BLToolkit 中的 Try-catch 不能标记为答案 - 我不是他们团队的成员 :)
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
(sender, eventArgs) => Console.WriteLine("unHandled " + eventArgs.ExceptionObject.GetType().FullName);
try
{
try
{
var instance = Activator.CreateInstance(typeof(ComponentExecutor));
MethodInfo mi = typeof(ComponentExecutor).GetMethod("Do");
BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly |
BindingFlags.InvokeMethod;
mi.Invoke(instance, bf, null, new object[0], CultureInfo.InvariantCulture);
}
catch (TargetInvocationException tarEx)
{
throw tarEx.InnerException;
}
}
catch (Exception ex)
{
Console.WriteLine("Handled " + ex.GetType().FullName);
}
}
class ComponentExecutor
{
public void Do()
{
new TestComponent().Do();
}
}
class TestComponent : Component
{
static TestComponent()
{
throw new NullReferenceException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Do()
{
Console.WriteLine("Doing");
}
protected override void Dispose(bool disposing)
{
Console.WriteLine("Disposing");
base.Dispose(disposing);
}
}
}
【问题讨论】:
-
哦,这很有趣
-
我在 connect 上记录了这个:connect.microsoft.com/VisualStudio/feedback/details/638078
标签: c# garbage-collection