我有一個控制器有3個方法具有相同的方法體。唯一的區別是方法類型。我有一個泛型類型的接口,我正在注入控制器。我正在注入接口,因爲我正在使用IoC(StructureMap)。使用泛型與web api控制器
問題是,控制器方法的返回類型與我的界面中方法的泛型類型不匹配。 (GetStatistics1
和GetStatistics2
)
爲了演示目的,我更改了第三種方法(GetStatistics3
)。我已經將返回類型從IEnumerable<T>
鑄造成IEnumerable<Type3>
。代碼編譯,但我不知道這是否是最有效的或雄辯的解決方案。
的代碼如下:
接口:
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;
}
}
附註:我本來試圖用[協方差(https://msdn.microsoft.com/en-us/library/dd799517(V解決這個= vs.110).aspx),但我無法弄清楚。 – Scott
謝謝Scott。我會檢查出來的。 – user1647160