【发布时间】:2016-03-03 23:26:19
【问题描述】:
我在 stackoverflow 上看到了一些类似问题的解决方案,但看起来每个问题都是独一无二的。
我正在尝试实现全局 try/catch,而不是在每个方法上都编写 try/catch,但我遇到了这个错误。它适用于一个参数,但不适用于采用多个参数的方法。
class Program
{
static void Main(string[] args)
{
int i = 5;
int j = 10;
string s1 = GlobalTryCatch(x => square(i), i);
string s2 = GlobalTryCatch(x => Sum(i,j), i, j); // error here..
Console.Read();
}
private static string square(int i)
{
Console.WriteLine(i * i);
return "1";
}
private static string Sum(int i, int j)
{
Console.WriteLine(i+j);
return "1";
}
private static string GlobalTryCatch<T1>(Func<T1, string> action, T1 i)
{
try
{
action.Invoke(i);
return "success";
}
catch (Exception e)
{
return "failure";
}
}
private static string GlobalTryCatch<T1, T2>(Func<T1, T2, string> action, T1 i, T2 j)
{
try
{
action.Invoke(i, j);
return "success";
}
catch (Exception e)
{
return "failure";
}
}
}
【问题讨论】:
-
I am stuck with this error这是什么错误? -
它给出了编译器错误“Delegate 'System.Func
' does not take 1 arguments” -
“我正在尝试实现全局 try/catch,而不是在每个方法上都编写 try/catch”。这些都没有任何意义。第一个对于除了日志记录之外的任何事情都是毫无意义的,因为它太笼统而无法处理出了什么问题。后者太宽了,因为大多数调用不应该抛出,并且许多最好通过让它依次传递给调用者来处理。
-
“而不是在每个方法上都写 try/catch” - 你根本不应该这样做。您应该只捕获可以合理处理的异常。阅读 Eric Lippert 的 Vexing exceptions。