我的许多服务方法都遵循这种模式:
public async Task<ApiResponseDto> DoSomething(string parameter1, string parameter2) // differing parameters
{
try // repeated
{
using (var db = new DbContext()) // repeated
{
// do stuff - this is where the unique stuff is
}
}
catch(Exception e){ // repeated
HandleServiceLayerException();
}
}
有什么方法可以将其提取到“足迹”中,这样我就不必为每个服务层方法重复这大约 10 行代码了吗?
最佳答案
你可以使用 Func<DbContext, Task<ApiResponseDto>>
,例如:
public async Task<ApiResponseDto> DBHelper(Func<DbContext,Task<ApiResponseDto>> apiRes) // differing parameters
{
try // repeated
{
using (var db = new DbContext()) // repeated
{
// do stuff - this is where the unique stuff is
var result = await apiRes(db);
return result;
}
}
catch (Exception e)
{ // repeated
HandleServiceLayerException();
return null;
}
}
然后为了使用它,你可以像这样定义一个函数:
public async Task<ApiResponseDto> DoDBStuff(DbContext db)
{
// Do specific stuff
}
然后像这样调用它:
private async void Button_Click()
{
await DBHelper(DoDBStuff);
}
关于c# - 如何在 C# 中合并/提取重复的代码结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315576/