簡體   English   中英

如何接受任何委托作為參數

[英]How to accept ANY delegate as a parameter

我有興趣編寫一個方法,接受另一個方法作為參數,但不想被鎖定到特定的簽名 - 因為我不關心這一點。 我只對該方法在調用時是否拋出異常感興趣。 .NET Framework中是否有一個構造允許我接受任何委托作為參數?

例如,以下所有調用都應該有效(不使用重載!):

DoesItThrowException(doSomething(arg));
DoesItThrowException(doSomethingElse(arg1, arg2, arg3, arg4, arg5));
DoesItThrowException(doNothing());

除非你給它參數,否則你不能調用它; 除非你知道簽名,否則你不能給它參數。 為了解決這個問題,我會把這個負擔放在調用者身上 - 我會使用Action和anon-methods / lambdas,即

DoesItThrowException(FirstMethod); // no args, "as is"
DoesItThrowException(() => SecondMethod(arg)); 
DoesItThrowException(() => ThirdMethod(arg1, arg2, arg3, arg4, arg5));

否則,您可以使用DelegateDynamicInvoke ,但這很慢,您需要知道提供它的args。

public static bool DoesItThrowException(Action action) {
    if (action == null) throw new ArgumentNullException("action");
    try {
        action();
        return false;
    } catch {
        return true;
    }
}
bool DoesItThrowException(Action a)
{
  try
  {
    a();
    return false;
  }  
  catch
  {
    return true;
  }
}

DoesItThrowException(delegate { desomething(); });

//or

DoesItThrowException(() => desomething());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM