2016-03-03 13 views
0

我看到了類似問題的stackoverflow上的一些解決方案,但看起來像每個問題是唯一的。代表'System.Func <int,int,string>'不帶1個參數

我想實現全球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"; 
      } 
     } 
    } 
+0

'我被這個錯誤卡住了'是什麼錯誤? –

+0

這是給編譯器錯誤「委託'System.Func '不帶1個參數」 –

+0

「我試圖實現全球try/catch而不是寫每個方法try/catch」。這些都沒有任何意義。第一種對於除伐木以外的任何事物都是毫無意義的,因爲它太籠統,無法處理髮生了什麼問題。後者太寬,因爲大多數呼叫不應該丟掉,而許多呼叫可以通過輪流給呼叫者來處理。 –

回答

3
string s2 = GlobalTryCatch((x, y) => Sum(i, j), i, j); 

編譯器無法string GlobalTryCatch<T1>(Func<T1, string> action, T1 i)你原來的方法匹配,因爲您的lambda表達式只有一個參數,但該方法的簽名要求兩個參數。解決方法是使用(x, y),這表示lambda採用兩個參數。

作爲快捷方式,你可以提供「方法組」,這將導致如下:

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

yeap ..它工作.. –

0

您可能需要考慮處理Application.UnhandledException事件並處理您的異常。

您的方法簽名不同。這就是爲什麼你不能使用GlobalTryCatch的單個實現。

1

您可以提供兩個參數的函數功能類似這樣的

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

有不需要添加lambda表達式。

相關問題