0

我尝试创建的泛型方法的签名存在问题。

课程如下:

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?)

基于我限制TMarketDataPoint. 所以,我想我可以返回一个IEnumerableof 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>();
    }
}
4

2 回答 2

5

这不起作用的原因是因为T可以.MarketDataPoint

如果您有S派生自的类MarketDataPoint并且有人调用,那么当您所拥有的只是 s 的集合时,GetMarketData<S>您如何给他们一个?IEnumerable<S>MarketDataPoint

编辑:正如马特本人指出的那样,您可以链接一个调用OfType<T>(),它将清除非T元素返回正确类型的IEnumerable.

return _dbContext.MarketDataPoints
    .Where(
        x => x.ReferenceDateTime >= startDateTime &&
        x.ReferenceDateTime <= endDateTime)
    .OfType<T>()
    .ToList();
于 2012-11-02T08:08:22.827 回答
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>

于 2012-11-02T08:10:41.080 回答