我正在尝试创建泛型方法的签名问题。
课程如下:
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
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>();
}
}
答案 0 :(得分:5)
这不起作用的原因是因为T
可以更具体而不是MarketDataPoint
。
如果您的课程S
来自MarketDataPoint
且有人致电GetMarketData<S>
,那么当您拥有的IEnumerable<S>
是MarketDataPoint
的集合时,如何为他们提供OfType<T>()
1}} S'
T
来清除非IEnumerable
元素和返回正确类型的{{ 1}}。
return _dbContext.MarketDataPoints
.Where(
x => x.ReferenceDateTime >= startDateTime &&
x.ReferenceDateTime <= endDateTime)
.OfType<T>()
.ToList();
答案 1 :(得分:0)
如果您按照错误并手动投射IEnumerable<T>
?
public IEnumerable<T> GetMarketData<T>(DateTime startDateTime, DateTime endDateTime) where T : MarketDataPoint
{
return (IEnumerable<T>)_dbContext.MarketDataPoints.Where(x => x.ReferenceDateTime >= startDateTime && x.ReferenceDateTime <= endDateTime).ToList();
}
问题是IEnumerable<MarketDataPoint>
与IEnumerable<T>
不同。