这个委托用法的目的是什么?

4

在使用 .NET 反编译器查看一个没有源代码的应用程序的代码时,我发现了这个:

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 },如果经常使用它吗?
2个回答

5

出现这个问题的原因似乎是为了有一个处理和记录操作错误的单一函数:bestEffort。代理被用来包装可能失败的操作并将其传递给bestEffort函数。


是的,那正是我想的。谢谢。 - Kev

1
一个委托可以作为参数传递给另一个函数。接收函数不需要知道哪个类公开了该函数,它可以调用它并像普通方法一样使用其结果。Lambda和表达式树都是基于委托构建的。常规函数无法在运行时评估,但可以通过使用委托创建表达式树来实现。您已经得到了您具体问题的答案,所以我将只添加问题的一般思路。

谢谢回答,我对委托、Lambda表达式和所有这些好东西都很了解,只是从未遇到过这种用法。 - Kev
好的,抱歉,您在stackoverflow上的积分水平应该在我发帖之前告诉我 :) - dexter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接