问题描述
我看到了一些关于stackoverflow的类似问题的解决方案,但是看起来每个问题都是唯一的.
I saw some solutions on stackoverflow for similar issues but looks like each problem is unique.
我正在尝试实现全局try/catch,而不是在每个方法上都编写try/catch,但是我一直陷在这个错误中.它适用于一个参数,而不适用于采用多个参数的方法.
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. 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);
编译器无法将原始方法与string GlobalTryCatch<T1>(Func<T1, string> action, T1 i)
匹配,因为您的lambda表达式只有一个参数,但是方法签名需要两个参数.解决方法是使用(x, y)
,它表示lambda接受两个参数.
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. The fix is to use (x, y)
, which indicates that the lambda is taking two arguments.
作为快捷方式,您可以仅提供方法组",这将导致以下结果:
As a shortcut, you can just provide the "method group", which would result in the following:
string s2 = GlobalTryCatch(Sum, i, j);
这篇关于委托'System.Func< int,int,string>'不带1个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!