Invalid variance: The type parameter 'T' must be invariantly valid on 'xxx.IItem<T>.GetList()'. 'T' is covariant [duplicate]

元气小坏坏 提交于 2020-01-05 04:02:11

问题


Why the following code get the error?

Invalid variance: The type parameter 'T' must be invariantly valid on 'UserQuery.IItem<T>.GetList()'. 'T' is covariant.

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

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

回答1:


The interfaces IBar and IItem do not agree on variance: in your IBar declaration, the T is not covariant, as there is no out keyword, whereas in IITem the T is covariant.




回答2:


The following code will get rid of the error.

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

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


来源:https://stackoverflow.com/questions/12484293/invalid-variance-the-type-parameter-t-must-be-invariantly-valid-on-xxx-iitem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!