我在控制器代码中有以下代码:
public async TaskPullClientsAsync() { var service = new DesktopConnectorService ( new WapiRepository (), new QuickBooksRepository ()); var filter = new ClientSearchFilter(); try { var items = await service.GetItemsAsync(filter); return items.Count; } catch (Exception ex) { } return 0; } public async Task PullInvoicesAsync() { var service = new DesktopConnectorService ( new WapiRepository (), new QuickBooksRepository ()); var filter = new InvoicesSearchFilter(); try { var items = await service.GetItemsAsync(filter); return items.Count; } catch (Exception ex) { } return 0; } public async Task PullPaymentsAsync() { var service = new DesktopConnectorService ( new WapiRepository (), new QuickBooksRepository ()); var filter = new PaymentSearchFilter(); try { var items = await service.GetItemsAsync(filter); return items.Count; } catch (Exception ex) { } return 0; }
如您所见,它有三种类型(ClientModel,PaymentModel和Invoices模型).上面的很多代码都在重复.
但我相信它可以简化.知道如何实现吗?
谢谢
如果所有模型和过滤器共享一个公共接口/基类,您可以:
public async TaskPullAsync () where TModel : IModel, where TFilter : IFilter, new(); { var service = new DesktopConnectorService ( new WapiRepository (), new QuickBooksRepository ()); var filter = new TFilter(); try { var items = await service.GetItemsAsync(filter); return items.Count; } catch (Exception ex) { } return 0; }
附注 - 不要使用这样的空捕获块,它们会吞下异常,因此很难诊断出以后可能发生的问题.至少在那里有一个日志记录声明,或做一些有意义的事情.否则,我会删除它.