问题
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