讓我們說我們有這樣的事:如何使方法自動覆蓋在嘗試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將等於「假」
C#不支持開箱即用。 –
您可以將try catch移至調用者邏輯嗎?或者這是開箱的? – Miguel
C#不支持開箱即用的裝飾器。您可以創建一個屬性,但最後,您需要檢查屬性的存在並執行您自己的邏輯。 – Miguel