方差无效:类型参数“T”必须在“UserQuery.IItem .ItemList”上有效。 ‘T’是协变的
为什么属性在编译方法时会出错?
public interface IFoo {} public interface IBar where T : IFoo {} public interface IItem where T: IFoo { // IEnumerable<IBar> GetList(); // works IEnumerable<IBar> ItemList { get; set; } // Error! }
错误:
方差无效:类型参数“T”必须在“UserQuery.IItem .ItemList”上有效。 ‘T’是协变的。
您收到编译器错误,因为您有一个属性getter( get
)和一个setter( set
)。 属性getter在其输出中具有T
,因此out
工作,但属性setter将在其输入中具有T
,因此它将需要in
修饰符。
因为你有T
你需要删除setter,它将编译:
public interface IItem where T : IFoo { // IEnumerable> GetList(); // works IEnumerable> ItemList { get; } // also works }
如果你的T
是generics参数,则以下内容可行:
public interface IItem where T : IFoo { IEnumerable> ItemList { set; } }
但是你不能同时拥有( out,in
)两者out,in
所以你不能拥有getter和setter的co / contravariant属性。
不允许使用setter,因为如果是这样的话你可以这样做:
public interface ISubFoo : IFoo { } IItem item = //whatever item.ItemList = new List>>();
这不是类型安全的。