我有很多WebService方法,都包含一些模板代碼,將實際工作封裝在try/catch/finally中,並在catch/finally中執行相同的任務。所以作爲封裝所有共享catch/finally的東西的一種方式,我寫了一個簡單的泛型。使用泛型來封裝通用方法的工作
這個工作,真的消除了一堆重複的代碼,但感覺klunky,語法非常鈍。每當我回到這個時候,我的大腦都會扭曲,試圖弄清楚它(一個明顯的跡象表明它不是一個好的設計)。我在尋找關於這是否是一件瘋狂事情的反饋,以及是否有更好的方法來處理它。
這裏是我的模板:
public delegate T2 RestfulServiceRequest<T1, T2>(T1 req);
static class RestfulService
{
public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req)
{
if (req == null)
throw new BadRequestException(new ArgumentNullException("Invalid or missing request object"));
try
{
return serviceCall(req);
}
catch (RestfulException e)
{
// log it and rethrow
Logger.Write(e);
throw;
}
catch (Exception e)
{
Logger.Error(e);
// wrap in a consistent exception for propagation back to caller
throw new InternalServerException(e);
}
finally
{
Logger.Debug("Complete");
}
}
}
}
這裏是它的用法:
public class Initialization : IInitialization
{
// MyMethod thas uses the template
public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req)
{
return RestfulService.ExceptionHandler<ApplianceInitReq, ApplianceInitResp>(delegate(ApplianceInitReq x)
{
// do some work
return new ApplianceInitResp();
}, req);
}
}
}
我不得不承認,我不明白'這個T1請求'是如何工作的。編譯器如何找出使用正確的泛型? – BrettRobi 2008-12-18 19:20:53