2017-08-24 21 views
1

讓我們說我們有這樣的事:如何使方法自動覆蓋在嘗試catch塊

public CustomType DoSomething1() { 
    CustomType ct = new CustomType(); 
    try { 
     // do something 
    } 
    catch(Exception e) { 
     ct.Passed = false; 
    } 
    return ct; 
} 

public CustomType DoSomething2() { 
    CustomType ct = new CustomType(); 
    try { 
     // do something 
    } 
    catch(Exception e) { 
     ct.Passed = false; 
    } 
    return ct; 
} 

public CustomType DoSomething3() { 
    CustomType ct = new CustomType(); 
    try { 
     // do something 
    } 
    catch(Exception e) { 
     ct.Passed = false; 
    } 
    return ct; 
} 

這些方法是由另一程序使用反射執行,如果CustomType屬性傳遞== false時,程序停止執行另一個。這是建築方面的原因。

是否有可能創建一些屬性或類似的東西來避免使用try catch,以便如果在方法中引發異常,它將使Passed屬性爲false並返回程序?例如。

[CatchException('Passed', false)] 
public CustomType DoSomething1() { 
    CustomType ct = new CustomType(); 
    // do something 
    return ct; 
} 

如果在過程中「有所作爲」的錯誤將會被拋出ct.Passed將等於「假」

+3

C#不支持開箱即用。 –

+0

您可以將try catch移至調用者邏輯嗎?或者這是開箱的? – Miguel

+0

C#不支持開箱即用的裝飾器。您可以創建一個屬性,但最後,您需要檢查屬性的存在並執行您自己的邏輯。 – Miguel

回答

0

如果我理解你的問題是正確的,你想避免重複在try-catch -塊。你可以通過創建一個你正在傳遞你想處理的邏輯的函數來解決這個問題。

public static CustomType CatchException(Action a) 
{ 
    CustomType ct = new CustomType(); 
    try 
    { 
     a(); 
    } 
    catch 
    { 
     ct.Passed = false; 
    } 
    return ct; 
} 

現在,你可以簡單地調用你需要像多次在一個非常舒適的方式任何邏輯功能。

public CustomType DoSomething1() 
{ 
    return CatchException(() => 
    { 
     //Do something 
    }); 
} 
... 
+0

返回類型怎麼樣,這種方法只適用於'void'方法嗎? – r1verside

+0

返回類型在我的第一個鏡頭中丟失。我已經在@ r1verside添加了它 – Fruchtzwerg

1

你可以做到以下幾點:

public static T SafeProcessing<T>(Action<T> action, Action<T> onFail) 
    where T: new() 
{ 
    var t = new T(); 

    try 
    { 
     a(t); 
    } 
    catch (Exception e) 
    { 
      //Log e 
      onFail(t); 
    } 

    return t; 
} 

而且沒有你會使用這樣的:

return SafeProcessing(c => DoSomething(c), c => c.Safe = false);