如何接受任何委托作为参数

时间:2009-12-09 20:18:01

标签: c# .net delegates

我有兴趣编写一个接受另一个方法作为参数但不想被锁定到特定签名的方法 - 因为我不关心这个。我只对该方法在调用时是否抛出异常感兴趣。 .NET Framework中是否有一个构造允许我接受任何委托作为参数?

例如,所有以下调用都应该有效(不使用重载!):

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

2 个答案:

答案 0 :(得分:12)

除非你给出论据,否则你不能调用它;除非你知道签名,否则你不能给它参数。为了解决这个问题,我会把这个负担放在调用者身上 - 我会使用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;
    }
}

答案 1 :(得分:3)

bool DoesItThrowException(Action a)
{
  try
  {
    a();
    return false;
  }  
  catch
  {
    return true;
  }
}

DoesItThrowException(delegate { desomething(); });

//or

DoesItThrowException(() => desomething());
相关问题