c# - 如何在 C# 中合并/提取重复的代码结构

标签 c# .net c#-4.0

我的许多服务方法都遵循这种模式:

  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/

相关文章:

c# - .NET Core JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions) 无法从 WebSocket ReceiveAsync 解析

c# - 如何仅使用 AspNet.Identity 在站点之间发送和接收身份验证票

c# - 移动游戏对象的最佳方式是什么,而不是传送它?

.net - 自动/智能插入 "itself"对象

c# - 枚举的显示文本

c# - 使用 Json.Net 解析谷歌地图地理编码 json 对对象的响应

.net - OrderBy、GetNewBindingList 和 Linq to SQL

.net - 如何告诉我的 .NET 应用程序要从哪个 IP 地址请求?

Web API Controller 方法的 LINQ 查询 JOIN 两个表

.net - 为什么不推荐在 C# 中使用默认编码?