方差无效:类型参数“T”必须在'xxx.IItem <t> .GetList()'上不变地有效。 'T'是协变的</t>

时间:2012-09-18 20:14:22

标签: c# covariance

为什么以下代码会出错?

  

无效方差:类型参数“T”必须是无效的   'UserQuery.IItem&LT; T&GT; .GetList()'。 'T'是协变的。

public interface IFoo {}
public interface IBar<T> where T : IFoo {}

public interface IItem<out T> where T: IFoo
{
    IEnumerable<IBar<T>> GetList();
}

2 个答案:

答案 0 :(得分:6)

接口IBarIItem不同意差异:在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();
}