簡體   English   中英

為什么泛型轉換在此部分代碼上不起作用?

[英]Why Generic Casting is not working on this section of code?

IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
  IQueryable<object> list = _repository.GetAllBuckets().Cast<object>().AsQueryable();
  return list == null ? default(T) : (T)list;
}

這是錯誤:錯誤3無法將類型'T'隱式轉換為'System.Linq.IQueryable'。 存在顯式轉換(您是否缺少演員表?)

我正在實現此接口:

 IQueryable<T> FindAllBuckets<T>();

問題是什么?

這是我嘗試過的:

  1.  IQueryable<T> IS3Repository.FindAllBuckets<T>() { IQueryable<object> list = _repository .GetAllBuckets() .Cast<object>().AsQueryable(); return list == null ? list.DefaultIfEmpty().AsQueryable() : list; } 

您正在將list強制轉換為T但是FindAllBuckets的返回值類型為IQueryable<T>

根據_repository.GetAllBuckets()的返回類型,這應該可以工作:

IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
    return _repository.GetAllBuckets()
                      .Cast<T>()
                      .AsQueryable();
}

嘗試這個:

IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
    IQueryable<T> list = _repository
                         .GetAllBuckets()
                         .Cast<T>()
                         .AsQueryable();

    return list ?? new List<T>().AsQueryable();
}

原始方法的主要問題是您試圖返回T的實例,而不是IQueryable<T>的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM