我有兴趣编写一个方法,该方法可以接受另一个方法作为参数,但不想被锁定到特定的签名中 - 因为我不关心这个。我只对方法在调用时是否抛出异常感兴趣。 .NET Framework 中是否有允许我接受任何委托(delegate)作为参数的结构?
例如,以下所有调用都应该有效(无需使用重载!):
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));
否则,您可以使用 Delegate
和 DynamicInvoke
,但这很慢,您需要知道要给它哪些参数。
public static bool DoesItThrowException(Action action) {
if (action == null) throw new ArgumentNullException("action");
try {
action();
return false;
} catch {
return true;
}
}
关于c# - 如何接受任何委托(delegate)作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1876589/