通过使用泛型避免中的代码重复

本文关键字:代码 泛型 | 更新日期: 2023-09-27 18:25:53

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

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模型)。上面的许多代码都在重复。

但我相信它可以被简化。知道如何做到这一点吗?

感谢

通过使用泛型避免中的代码重复

如果所有模型和过滤器都共享一个公共接口/基类,则可以执行以下操作:

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;
}

旁注-不要像那样使用空的catch块,它们会吞下异常,这使得诊断稍后可能发生的问题变得非常困难。至少有一个日志记录语句,或者做一些有意义的事情。否则,我会删除它。