c# - Delegate.DynamicInvoke - 捕获异常

标签 c# exception delegates

我正在使用以下方式调用委托(delegate)(动态可配置服务):

public void CallService (Delegate service, IContext ctx)
{
    var serviceArgs = CreateServiceArguments(service, ctx);
    service.DynamicInvoke(serviceArgs);
}

此时我想捕获在被调用的服务方法中发生的所有异常,但是,我不想捕获由于 DynamicInvoke 调用而发生的任何异常。例如:

  • service 委托(delegate)抛出 DomainException -> 捕获异常
  • DynamicInvoke() 抛出 MemberAccessException 因为委托(delegate)是私有(private)方法 -> 不要捕获异常,让它冒泡

我希望我的问题很清楚。如何确定捕获的异常是源自 DynamicInvoke 调用本身还是源自底层委托(delegate)。

哦,是的,而且:我不能使用异常类型来决定!服务本身也完全有可能抛出 MemberAccessException,因为它本身可以执行一些委托(delegate)操作...

最佳答案

Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...

是的,您可以使用异常类型来决定。正如 Delegate.DynamicInvoke 的文档中提到的,如果被调用的方法抛出异常(任何异常),它将被包装在 TargetInvocationException 中。这是您可以捕获的异常,然后您可以查看其 InnerException 属性来了解它是否是您可以处理的异常。

关于c# - Delegate.DynamicInvoke - 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954407/

相关文章:

c# - 使用 WCF 生成 JSON 数组

java - EJB 3.1 - 处理异步作业中的异常

ios - 委托(delegate)优势

c# - 将事件处理程序作为方法参数传递

c# - 从传递字节数组的 C# 调用 delphi dll 函数

c# - 从一个 winform 切换到另一个时面板闪烁

java - SolrJ 没有捕获 SolrException

php - 如何知道异常来自PHP的行号

c# - 如果事件在 .NET 中作为委托(delegate)实现,那么 .event IL 部分的意义何在?

c# - WPF TextBox 被切断