私は、同じメソッド本体を持つ3つのメソッドを持つコントローラを持っています。唯一の違いは、メソッドタイプです。私はコントローラーに注入しているジェネリックタイプのインターフェースを持っています。私はIoC(StructureMap)を使用しているため、インターフェイスを注入しています。Web APIコントロールを使用したジェネリックを使用
問題は、コントローラメソッドの戻り値の型が、インターフェイスのメソッドの汎用型と一致しないことです。 (GetStatistics1
およびGetStatistics2
)
デモンストレーションの目的で、私は第3の方法(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