为什么我会收到"类型参数必须是有效目不暇接..."错误? [英] Why am I getting "The type parameter must be invariantly valid..." error?
问题描述
我将试图缩短这个代码示例:
公共接口IThing
{
/ / ...的东西
}
公共类Thing1:IThing
{
}
公共类Thing2:IThing
{
}
公共接口IThingView<出T>
{
ICollection的< T>查看全部();
}
公共类ThingView< T> :IThingView< T>
{
ICollection的< T> ViewAll(){返回新的List< T>(); } //这里有一个很大的操作
}
公共接口IThingViewerFactory
{
公共IThingView< IThing>构建(字符串,);
}
公共类ThingViewerFactory
{
公共IThingView< IThing>建(字符串,)
{
如果(Which.Equals(Thing1){返回新(IThingView< IThing>)新ThingViewer< Thing1>();}
,否则{返回新(IThingView< IThing>)新ThingViewer< Thing2>();}
}
}
这就是我在做什么,我有很多需要观众,这将遵循COMON接口类的东西的一个粗略的想法,我想一个工厂由我传递一个字符串与产生这些名字我不断收到一个编译器错误抱怨:
无效差异:该类型参数'T'必须是'IThingView.ViewAll()'目不暇接有效的'T 是协变的。
我知道即使我得到这个工作,我会在事后做一些铸造......我很好这一点。我意识到这种方法极有可能没有必要了。在这一点上这一点变得越来越骄傲/好奇的问题。
谢谢!
< DIV CLASS =h2_lin>解决方案
您不能让一个协变的ICollection< T>
,因为它允许你把 T
s转换它。
您可以做一个协变的只读集合,一个逆变只写集合,或一个不变读集合。写结果
你不能两者都做,也不会是类型安全的。
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' is covariant.
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.
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.
这篇关于为什么我会收到"类型参数必须是有效目不暇接..."错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!