[英]Delegate 'System.Func<int,int,string>' does not take 1 arguments
I saw some solutions on stackoverflow for similar issues but looks like each problem is unique. 我看到了一些针对stackoverflow的类似问题的解决方案,但看起来每个问题都是唯一的。
I am trying to implement global try/catch instead of writing try/catch on each and every method but I am stuck with this error. 我试图实现全局try / catch而不是在每个方法上都编写try / catch,但是我被这个错误所困扰。 It's working fine for one argument and not working for methods taking more than one argument.
它仅适用于一个参数,而不适用于采用多个参数的方法。
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";
}
}
}
string s2 = GlobalTryCatch((x, y) => Sum(i, j), i, j);
The compiler couldn't match your original method with string GlobalTryCatch<T1>(Func<T1, string> action, T1 i)
because your lambda expression only had one argument, but the method signature calls for two arguments. 编译器无法将您的原始方法与
string GlobalTryCatch<T1>(Func<T1, string> action, T1 i)
因为您的lambda表达式只有一个参数,但是方法签名需要两个参数。 The fix is to use (x, y)
, which indicates that the lambda is taking two arguments. 解决方法是使用
(x, y)
,它表示lambda接受两个参数。
As a shortcut, you can just provide the "method group", which would result in the following: 作为快捷方式,您可以仅提供“方法组”,这将导致以下结果:
string s2 = GlobalTryCatch(Sum, i, j);
You can provide your two-parameter Func like this 您可以像这样提供您的两参数Func
string s2 = GlobalTryCatch(Sum, i, j); // error here..
There is no need to add a lambda expression. 无需添加lambda表达式。
You might want to consider handling Application.UnhandledException event and handle your exceptions there. 您可能要考虑处理Application.UnhandledException事件并在那里处理您的异常。
Your method signatures differ. 您的方法签名不同。 That is why you cannot use a single implementation of GlobalTryCatch.
这就是为什么您不能使用GlobalTryCatch的单个实现的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.