简体   繁体   中英

Cannot convert IEnumerable<Class1> to IEnumerable<T>?

The following code will get two errors on parameter p1 and p2 of method call NewMethod<T>(p1, p2); .

  1. p1 : Cannot convert IQueryable<ICollection<Class1>> to IQueryable<ICollection<T>> ?
  2. p2 : Cannot convert IEnumerable<Class1> to IEnumerable<T>

How to fix the method call?

public interface IBase<out T> { T Prop1 { get; } }
class Class1 : IBase<int> { public int Prop1 { get; set; } }

static IEnumerable<T> NewMethod<T, U>(IQueryable<ICollection<T>> exist, IEnumerable<T> bs)
where T : IBase<U>
{
    return null;
}

public IEnumerable<T> Existed<T>(IEnumerable<T> p2) 
{
  .....
  if (typeof(T) == typeof(Class1)) {
    IQueryable<ICollection<T>> p1 = null;
    return result = NewMethod<Class1, int>(p1, p2);
  } .....
}

Is it a co-variance or contra-variance issue?

Disclaimer:

The OP originally asked a question about why generics were not working with ICollection<T> . After I answered, the OP changed to ask different questions about IEnumerable<T> , so this answer no longer applies.

Is it a co-variance or contra-variance issue?

Yes, since ICollection<T> is not covariant, the compiler cannot substitute Class1 for IBase<U> .

Try using IEnumerable<T> instead of ICollection<T> ( IEnumerable<T> is covariant).

Why can't you do this?

public IEnumerable<T> Existed<T, U>(IEnumerable<T> bands) where T : IBase<U> {
  IQueryable<IEnumerable<T>> p1 = null;
  IEnumerable<T> p2 = null;
  return NewMethod<T, U>(p1, p2);
}

It needs several type casting.

public IEnumerable<T> Existed<T>(IEnumerable<T> p2) // where T : IBase<U>
{
  if (typeof(T) == typeof(Class1)) {
    IQueryable<ICollection<T>> p1 = null;
    return NewMethod<Class1, int>( // Type parameter are assigned
        p1 as IQueryable<ICollection<Class1>>,
        p2 as IEnumerable<Class1>
    ) as IEnumerable<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