c# - 这个委托(delegate)用法的目的是什么?

标签 c# .net delegates

在使用 .NET Reflector 为我没有源代码的应用程序查找一些代码时,我发现了这个:

if (DeleteDisks)
{
  using (List<XenRef<VDI>>.Enumerator enumerator3 = list.GetEnumerator())
  {
    MethodInvoker invoker2 = null;
    XenRef<VDI> vdiRef;
    while (enumerator3.MoveNext())
    {
      vdiRef = enumerator3.Current;
      if (invoker2 == null)
      {
        //
        // Why do this?
        //
        invoker2 = delegate {
          VDI.destroy(session, vdiRef.opaque_ref);
        };
      }
      bestEffort(ref caught, invoker2);
    }
  }
}
if (caught != null)
{
  throw caught;
}


private static void bestEffort(ref Exception caught, MethodInvoker func)
{
  try
  {
    func();
  }
  catch (Exception exception)
  {
    log.Error(exception, exception);
    if (caught == null)
    {
      caught = exception;
    }
  }
}

为什么不直接调用VDI.destroy()?这只是一种包装相同模式的方法吗 try { do something } catch { log error } 如果它被大量使用?

最佳答案

原因似乎是只有一个函数可以处理和记录可能失败的操作中的错误:bestEffort。委托(delegate)用于包装可能失败的操作并将其传递给 bestEffort 函数。

关于c# - 这个委托(delegate)用法的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511157/

相关文章:

c# - 想要从下拉列表中的日期中删除时间?

c# - 两个字符整数到字符?

c# - 如何自动打印tiff文件?

c# - 如何使用 C# 编写 LINQ 查询以从另一个对象获取对象?

c# - Docker - 构建时未找到框架 microsoft.AspNetCore.App,版本 '3.1' 0

c# - 具有四个以上参数(方法参数)的 Action 委托(delegate)

c# - 在 .NET 中查找下一个 TCP 端口的线程安全方式(通过多个进程)

c# - 游戏中的对象如何交流

iOS:UIApplication DidReceiveRemoteNotification

ios - 为什么我的委托(delegate)变为零?