Son*_*ate 10 .net c# delegates
我有兴趣编写一个方法,接受另一个方法作为参数,但不想被锁定到特定的签名 - 因为我不关心这一点.我只对该方法在调用时是否抛出异常感兴趣..NET Framework中是否有一个构造允许我接受任何委托作为参数?
例如,以下所有调用都应该有效(不使用重载!):
DoesItThrowException(doSomething(arg));
DoesItThrowException(doSomethingElse(arg1, arg2, arg3, arg4, arg5));
DoesItThrowException(doNothing());
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 12
除非你给它参数,否则你不能调用它; 除非你知道签名,否则你不能给它参数.为了解决这个问题,我会把这个负担放在调用者身上 - 我会使用Action和anon-methods/lambdas,即
DoesItThrowException(FirstMethod); // no args, "as is"
DoesItThrowException(() => SecondMethod(arg));
DoesItThrowException(() => ThirdMethod(arg1, arg2, arg3, arg4, arg5));
Run Code Online (Sandbox Code Playgroud)
否则,你可以使用Delegate和DynamicInvoke,但这很慢,你需要知道给它的args.
public static bool DoesItThrowException(Action action) {
if (action == null) throw new ArgumentNullException("action");
try {
action();
return false;
} catch {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
bool DoesItThrowException(Action a)
{
try
{
a();
return false;
}
catch
{
return true;
}
}
DoesItThrowException(delegate { desomething(); });
//or
DoesItThrowException(() => desomething());
Run Code Online (Sandbox Code Playgroud)