[英]Why am I getting “The type parameter must be invariantly valid…” error?
I'll attempt to shorten this code example:我将尝试缩短此代码示例:
public interface IThing
{
//... Stuff
}
public class Thing1 : IThing
{
}
public class Thing2 : IThing
{
}
public interface IThingView<out T>
{
ICollection<T> ViewAll();
}
public class ThingView<T> : IThingView<T>
{
ICollection<T> ViewAll() { return new List<T>(); } // There's a big operation here
}
public interface IThingViewerFactory
{
public IThingView<IThing> Build(string Which);
}
public class ThingViewerFactory
{
public IThingView<IThing> Build(string Which)
{
if(Which.Equals("Thing1") { return new (IThingView<IThing>)new ThingViewer<Thing1>();}
else { return new (IThingView<IThing>)new ThingViewer<Thing2>();}
}
}
That's a rough idea of what I'm doing.这是我在做什么的一个粗略的想法。 I have a number of Thing classes that require a viewer, which will follow a comon interface.
我有许多需要查看器的事物类,它们将遵循一个通用接口。 I'd like a factory to generate these by me passing in a string with the name.
我想要一个工厂通过我传入一个带有名称的字符串来生成这些。 I keep getting a compiler error complaining:
我不断收到编译器错误抱怨:
Invalid variance: The type parameter 'T' must be invariantly valid on 'IThingView.ViewAll()'.无效方差:类型参数“T”必须在“IThingView.ViewAll()”上始终有效。 'T' is covariant.
“T”是协变的。
I realize even if I get this to work, I'll have to do some casting afterwards... I'm fine with that.我意识到即使我让这个工作,我之后也必须做一些铸造......我很好。 And I realize this approach is more than likely not necessary.
而且我意识到这种方法很可能没有必要。 At this point this has become more of a pride/curiosity issue.
在这一点上,这已成为更多的骄傲/好奇心问题。
Thanks!谢谢!
You cannot make a covariant ICollection<T>
, since it allows you to put T
s into it.您不能创建协变
ICollection<T>
,因为它允许您将T
放入其中。
You can make a covariant read-only collection, a contravariant write-only collection, or an invariant read-write collection.您可以创建协变只读集合、逆变只写集合或不变读写集合。
You can't do both, or it wouldn't be typesafe.你不能两者都做,否则它不会是类型安全的。
To expand on SLaks answer:要扩展 SLaks 答案:
To make your code compile, change the return type of ViewAll
from ICollection<T>
to IEnumerable<T>
.要编译您的代码,
ViewAll
的返回类型从ICollection<T>
更改为IEnumerable<T>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.