为什么以下代码会出错?
无效方差:类型参数“T”必须是无效的 'UserQuery.IItem< T> .GetList()'。 'T'是协变的。
public interface IFoo {}
public interface IBar<T> where T : IFoo {}
public interface IItem<out T> where T: IFoo
{
IEnumerable<IBar<T>> GetList();
}
答案 0 :(得分:6)
接口IBar
和IItem
不同意差异:在IBar
声明中,T不是协变的,因为没有out
关键字,而在IITem
T是协变的。
答案 1 :(得分:1)
以下代码将消除错误。
public interface IFoo {}
public interface IBar<out T> where T : IFoo {}
public interface IItem<out T> where T: IFoo
{
IEnumerable<IBar<T>> GetList();
}