避免在c#中重复代码 - 使用泛型?

时间:2015-12-07 09:58:10

标签: c# .net generics

我在控制器代码中有以下代码:

public async Task<int> PullClientsAsync()
{
    var service = new DesktopConnectorService<ClientModel>(
            new WapiRepository<ClientModel>(), new QuickBooksRepository<ClientModel>());
    var filter = new ClientSearchFilter();
    try
    {
        var items = await service.GetItemsAsync(filter);
        return items.Count;
    }
    catch (Exception ex)
    {


    }
    return 0;
}

public async Task<int> PullInvoicesAsync()
{
    var service = new DesktopConnectorService<InvoiceModel>(
        new WapiRepository<InvoiceModel>(), new QuickBooksRepository<InvoiceModel>());
    var filter = new InvoicesSearchFilter();
    try
    {
        var items = await service.GetItemsAsync(filter);
        return items.Count;
    }
    catch (Exception ex)
    {


    }
    return 0;
}

public async Task<int> PullPaymentsAsync()
{
    var service = new DesktopConnectorService<PaymentModel>(
        new WapiRepository<PaymentModel>(), new QuickBooksRepository<PaymentModel>());
    var filter = new PaymentSearchFilter();
    try
    {
        var items = await service.GetItemsAsync(filter);
        return items.Count;
    }
    catch (Exception ex)
    {


    }
    return 0;
}

正如您所看到的,它有三种类型(ClientModel,PaymentModel和Invoices模型)。上面有很多代码在重复。

但我相信它可以简化。知道如何实现这个目标吗?

由于

1 个答案:

答案 0 :(得分:7)

如果所有模型和过滤器共享一个公共接口/基类,您可以这样做:

public async Task<int> PullAsync<TModel, TFilter>() 
                       where TModel : IModel, 
                       where TFilter : IFilter, new();
{
    var service = new DesktopConnectorService<TModel>(
                    new WapiRepository<TModel>(), new QuickBooksRepository<TModel>());
    var filter = new TFilter();
    try
    {
        var items = await service.GetItemsAsync(filter);
        return items.Count;
    }
    catch (Exception ex)
    {
    }
    return 0;
}

旁注 - 不要使用像这样的空捕获块,它们会吞下异常,因此很难诊断出以后可能发生的问题。至少在那里有一个日志记录声明,或做一些有意义的事情。否则,我将其删除。