【问题标题】:Unable to convert IEnumerable<TEntity> to TCollection无法将 IEnumerable<TEntity> 转换为 TCollection
【发布时间】:2014-08-29 15:01:58
【问题描述】:

我定义了以下接口:

public interface IReadOnlyRepositoryBase<TEntity, TKey, TCollection>
    where TEntity : EntityBase<TKey>
    where TCollection: IEnumerable<TEntity>

{
    TCollection GetAll();
}

public interface IReadOnlyRepository<TEntity, TKey> :
    IReadOnlyRepositoryBase<TEntity, TKey, IEnumerable<TEntity>>
    where TEntity : EntityBase<TKey>
{ }

// there is also "ILazyReadOnlyRepository" where TCollection
// is IQueryable<T>..

现在我无法在我的实现中返回IEnumerable&lt;TEntity&gt;,因为IEnumerable&lt;TEntity&gt; 似乎无法转换为TCollection

// basic repository impl for NHibernate
public abstract class NHibernateReadOnlyRepositoryBase<TEntity, TKey, TCollection> 
    : IReadOnlyRepositoryBase<TEntity, TKey, TCollection>
    where TEntity : EntityBase<TKey>
    where TCollection : IEnumerable<TEntity>
{

    public TCollection GetAll()
    {
          // doesn't work...
          return _session.QueryOver<TEntity>().List();
    }    

据我所见,该方法返回一个实现IEnumerable&lt;T&gt;IList&lt;T&gt;,那么这显然应该有效吗?我怎样才能实现我想要的?

【问题讨论】:

  • 这应该如何工作? TCollection 也可以是 List&lt;TEntity&gt;,在这种情况下,您会将 IList&lt;TEntity&gt; 转换为 List&lt;TEntity&gt;。那是不可能的。

标签: c# linq generics collections repository


【解决方案1】:

您不应该使用通用参数TCollection。使用泛型参数是一种说法,即该接口的用户应该能够定义该类型是什么,在这种情况下,该方法返回什么类型。

显然这对你来说是个问题。您的方法实现需要无条件返回IEnumerable,而不是调用者指定的未知类型。只需删除该通用参数即可完成此操作。

public interface IReadOnlyRepositoryBase<TEntity, TKey>
    where TEntity : EntityBase<TKey>
{
    IQueryable<TEntity> GetAll();
}

【讨论】:

  • 但是这样我可以指定一个接口,该接口预计会返回一个 IQueryable,例如一个惰性存储库实现。
  • @xvdiff 然后定义它返回一个IQueryable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2019-02-08
相关资源
最近更新 更多