C# 将泛型与web api控制器一起使用

C# 将泛型与web api控制器一起使用,c#,generics,asp.net-web-api,interface,C#,Generics,Asp.net Web Api,Interface,我有一个控制器,它有3个具有相同方法体的方法。唯一的区别是方法类型。我有一个注入控制器的泛型类型接口。我注入接口是因为我使用的是IoC结构图 问题是控制器方法的返回类型与接口中方法的泛型类型不匹配。GetStatistics 1和GetStatistics 2 出于演示目的,我更改了第三种方法GetStatistics3。我已将返回类型从IEnumerable转换为IEnumerable。代码可以编译,但我不确定这是不是最有效或最有说服力的解决方案 代码如下: 接口: public interf

我有一个控制器,它有3个具有相同方法体的方法。唯一的区别是方法类型。我有一个注入控制器的泛型类型接口。我注入接口是因为我使用的是IoC结构图

问题是控制器方法的返回类型与接口中方法的泛型类型不匹配。GetStatistics 1和GetStatistics 2

出于演示目的,我更改了第三种方法GetStatistics3。我已将返回类型从IEnumerable转换为IEnumerable。代码可以编译,但我不确定这是不是最有效或最有说服力的解决方案

代码如下:

接口:

public interface IStatistics<T>
{
    IEnumerable<T> ExecStatistics_SP(DateTime ? date,
    int ? xd, string iap, int? statisticsType );
}
控制器:

public class StatisticsController : ApiController
{
    private readonly IStatistics<T> _repo;

    public StatisticsController(IStatistics<T> repo)
    {
        _repo = repo;
    }

    public IEnumerable<Type1> GetStatistics1(string iap, DateTime date, int? statisticsType, int xd)
    {
        return _repo.ExecStatistics_SP(date,xd,iap,statisticsType).AsEnumerable();
    }

    public IEnumerable<Type2> GetStatistics2(string aip, DateTime date, int? statisticsType, int xd)
    {
       return = _repo.ExecStatistics_SP(date, xd, iap, statisticsType).AsEnumerable();
    }

    public IEnumerable<Type3> GetStatistics3(string iap, DateTime date, int? statisticsType, int xd)
    {
        returnValue = _repo.ExecStatistics_SP(date,xd,iap,statisticsType).AsEnumerable();
        return (IEnumerable<Type3>) returnValue;
    }
}
TL;DR我怀疑这在Web API中是可能的;您最好为不同的类创建单独的控制器

代码本身的问题在于类定义。StatisticsController不知道t是什么,这意味着编译器无法检查ExecStatistics\u SP是否返回兼容类型

此外,由于IStatistics被注入到类中,因此没有办法区分每个方法中的T,除非您对每个调用都进行反思

另一种方法是让语言处理一切,并在此过程中简化类。使用此解决方案,StatisticsController的调用者知道T是什么,在您的示例中,T是Type1、Type2或Type3。实际上,T可以是实现IStatistic的任何类


旁注:我最初试图用解决这个问题,但我想不出来。谢谢斯科特。我去看看。
public class StatisticsController<T>
{
    private readonly IStatistics<T> _repo;

    public StatisticsController(IStatistics<T> repo)
    {
        _repo = repo;
    }

    public IEnumerable<T> GetStatistics(string iap, DateTime date, int? statisticsType, int xd)
    {
        return _repo.ExecStatistics_SP(date, xd, iap, statisticsType);
    }
}
var repo = new StatisticsRepo<Type1>();  // Made-up repo class
var controller = new StatisticsController<Type1>(repo);
IEnumerable<Type1> values = controller.GetStatistics(...);
// etc