首先,它聽起來像你可能經常使用try/catch - 特別是如果你正在捕捉Exception
。 try/catch塊應該比較少見;除非你真的可以「處理」這個異常,否則你應該讓它冒泡到堆棧的下一層。
現在,假設你真的做想要所有這些try/catch塊,爲什麼它不是一個創建委託的選項?通過匿名方法和lambda表達式,以及System
命名空間中的Func/Action委託,基本上沒有什麼工作要做。你寫:
public void SurroundWithTryCatch(Action action)
{
try
{
action();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
,然後你就會SurroundWithTryCatch(MyMethod)
正常工作,如果它沒有PARAMATERS。
或者,如果你不想調用不同方法做,只是寫:
public void MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
});
}
如果你需要從方法返回,你可以這樣做:
public int MyMethod()
{
return SurroundWithTryCatch(() =>
{
// Logic here
return 5;
});
}
SurroundWithTryCatch
的通用過載如下:
public T SurroundWithTryCatch<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
大多數情況下,在C#2中也可以,但類型推斷對你來說不會有太大的幫助,你必須使用匿名方法而不是lambda表達式。
但要回到起點:儘量少用try/catch。 (儘量/最後應該更頻繁,儘管通常寫成使用語句。)
@Jon ahh你打我它..DAM YOU;) – 2008-11-11 06:40:05