简体   繁体   中英

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

This is the error: Error 3 Cannot implicitly convert type 'T' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

I am implementing this interface:

 IQueryable<T> FindAllBuckets<T>();

What is the problem?

This is what I have tried:

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

You're casting list to T but the return value of FindAllBuckets is of type IQueryable<T> .

Depending on the return type of _repository.GetAllBuckets() , this should work:

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

Try this:

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

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

The main problem with your original approach is that you were trying to return an instance of T rather than an instance of IQueryable<T> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM