gpt4 book ai didi

c# - 在工厂中使用通用接口(interface)时推断类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:02 26 4
gpt4 key购买 nike

我和我的同事正在为在线店面构建一个小型报告框架。我们已经按照存储库模式构建了一个库,使用“报告”作为存储库和一个非常轻的服务层来与所述报告进行交互。我们的代码运行良好,而且非常易于使用。然而,有一件事困扰着我个人:在服务工厂级别,我们需要两次声明我们的返回类型(不是推断的)。这是我们项目的基础:

报告界面

这就是我们的“存储库”。它们接收数据访问对象,例如 SQL/Oracle 连接的包装器类,或我们店面的 API。

internal interface IReport<T>
{
T GetReportData(dynamic options);
}

存储库工厂

这提供了一种通过了解类型来生成这些报告的简单方法。

internal interface IReportFactory
{
TR GenerateNewReport<T, TR>() where TR : IReport<T>;
}

internal class ReportFactory : IReportFactory
{
public ReportFactory()
{
// some initialization stuff
}

public TR GenerateNewReport<T, TR>() where TR : IReport<T>
{
try
{
return (TR)Activator.CreateInstance(typeof(TR));
}
catch(Exception ex)
{
// Logging
}
}
}

示例报告(存储库)

这是一份报告的样子。请注意,它返回一个数据表,并在通用接口(interface)中用它声明(这将很快发挥作用)。

internal class ItemReport : IReport<DataTable>
{
public DataTable GetReportData(dynamic options)
{
return new DataTable();
}
}

报告服务

接收报告(存储库)并使用它的轻量级服务。轻,但它允许简单的单元测试等,如果我们想在检索报告后添加额外的处理,这样做很容易。

public interface IReportService<T>
{
T GetReportData(dynamic options);
}

public class ReportService<T> : IReportService<T>
{
private readonly IReport<T> _report;

public ReportService(IReport<T> report)
{
_report = report;
}

public T GetReportData(dynamic options)
{
return _report.GetReportData(options);
}
}

服务工厂

我们将服务工厂设置为抽象类(因为所有服务工厂都需要创建报表工厂),强制使用默认构造函数:

public abstract class ReportServiceFactory
{
protected IReportFactory ReportFactory;

protected ReportServiceFactory(connection strings and other stuff)
{
ReportFactory = new ReportFactory(connection strings and other stuff);
}
}

然后我们可以根据功能创建单独的服务工厂。例如,我们有一个“标准报告”服务工厂,以及客户特定的服务工厂。这里的实现是我的问题所在。

public class SpecificUserServiceFactory : ReportServiceFactory
{
public SpecificUserServiceFactory(connection strings and other stuff) : base(connection strings and other stuff){}

public IReport<DataTable> GetItemReport()
{
return new ReportService<DataTable>(ReportFactory.GenerateNewReport<DataTable, ItemReport>());
}
}

为什么我在创建服务工厂时必须如此冗长?我声明了两次返回类型。为什么我不能做这样的事情:

return new ReportService(ReportFactory.GenerateNewReport<ItemReport>());

请注意,我没有在此声明 DataTable;我认为应该从ItemReport是IReport这个事实来推断。非常感谢任何关于如何让它以这种方式工作的建议。

很抱歉问这么简单的问题需要这么长的解释,但我认为所有支持代码都有助于提出解决方案。再次感谢!

最佳答案

在调用 GenerateNewReport 时不能省略 DataTable 通用类型的原因是因为它是对该函数定义中其他通用类型的约束。让我们假设(为简单起见)您的 IReport 实际上是一个带有函数 void Something(T input) 的接口(interface)。一个类可以同时实现 IReport 和 IReport 。然后,我们构建这样一个名为 Foo 的类:IReport 、IReport 。编译器将无法编译 bar.GenerateNewReport ,因为它不知道它是否绑定(bind)到 IReport 或 IReport 类型,因此无法确定该调用的适当返回类型。

关于c# - 在工厂中使用通用接口(interface)时推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com