【问题标题】:Delegate 'System.Func<int,int,string>' does not take 1 arguments委托 'System.Func<int,int,string>' 不接受 1 个参数
【发布时间】: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

标签: c# linq lambda


【解决方案1】:
string s2 = GlobalTryCatch((x, y) => Sum(i, j), i, j);

编译器无法将您的原始方法与string GlobalTryCatch&lt;T1&gt;(Func&lt;T1, string&gt; action, T1 i) 匹配,因为您的 lambda 表达式只有一个参数,但方法签名需要两个参数。解决方法是使用(x, y),它表示 lambda 接受两个参数。

作为一种快捷方式,您可以只提供“方法组”,这将导致以下结果:

string s2 = GlobalTryCatch(Sum, i, j);

【讨论】:

    【解决方案2】:

    你可以像这样提供你的双参数函数

    string s2 = GlobalTryCatch(Sum, i, j); // error here..
    

    无需添加 lambda 表达式。

    【讨论】:

      【解决方案3】:

      您可能需要考虑处理Application.UnhandledException 事件并在那里处理您的异常。

      您的方法签名不同。这就是为什么不能使用 GlobalTryCatch 的单一实现的原因。

      【讨论】:

        猜你喜欢
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        相关资源
        最近更新 更多