我尝试创建的泛型方法的签名存在问题。
课程如下:
public class MarketDataRepository : IRepository
{
MarketWatchEntities _dbContext = new MarketWatchEntities();
public MarketDataRepository(){}
public MarketDataRepository(MarketWatchEntities dbContext)
{
_dbContext = dbContext;
}
public IEnumerable<T> GetMarketData<T>(DateTime startDateTime, DateTime endDateTime ) where T : MarketDataPoint
{
return _dbContext.MarketDataPoints.Where(x => x.ReferenceDateTime >= startDateTime && x.ReferenceDateTime <= endDateTime).ToList();
}
}
public interface IRepository
{
IEnumerable<T> GetMarketData<T>(DateTime startDateTime, DateTime endDateTime) where T : MarketDataPoint;
}
附加信息:
MarketWatchEntities
扩展DbContext
(由实体框架生成)。
我得到这个编译时异常:
Cannot implicitly convert type 'System.Collections.Generic.List<MarketWatcher.Domain.MarketDataPoint>' to 'System.Collections.Generic.IEnumerable<T>'. An explicit conversion exists (are you missing a cast?)
基于我限制T
从MarketDataPoint
. 所以,我想我可以返回一个IEnumerable
of MarketDataPoint
。
任何有关上述问题以及我应该做什么的指示将不胜感激!
解决方案(谢谢大家):
public class MarketDataMarketDataRepository : IMarketDataRepository
{
MarketWatchEntities _dbContext = new MarketWatchEntities();
public MarketDataMarketDataRepository(){}
public MarketDataMarketDataRepository(MarketWatchEntities dbContext)
{
_dbContext = dbContext;
}
public IQueryable<T> GetMarketData<T>(DateTime startDateTime, DateTime endDateTime ) where T : MarketDataPoint
{
return _dbContext.MarketDataPoints.Where(x => x.ReferenceDateTime >= startDateTime && x.ReferenceDateTime <= endDateTime).OfType<T>();
}
}