委托'System.Func< int,int,string>'不带1个参数

编程入门 行业动态 更新时间:2024-10-11 11:24:02
本文介绍了委托'System.Func< int,int,string>'不带1个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我看到了一些关于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&lt; int,int,string&gt;'不带1个参数

本文发布于:2023-11-12 12:57:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581558.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不带   参数   Func   amp   System

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!