C#通用方法声明

时间:2012-11-02 08:03:29

标签: c# generics inheritance

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

课程如下:

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>();
    }
}

2 个答案:

答案 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>不同。