如何管理一个C#泛型类,其类型是基类的容器? [英] How do you manage a C# Generics class where the type is a container of a base class?
问题描述
我得到以下错误
最好的重载方法匹配'System.Collections.Generic.List> .Add(MyContainer)'有一些无效的参数(CS1502 )(GenericsTest)
The best overloaded method match for `System.Collections.Generic.List>.Add(MyContainer)' has some invalid arguments (CS1502) (GenericsTest)
对于下面的类:
A和B是MyBase的子类。 p>
A and B are child classes of MyBase.
public class GenericConstraintsTest
{
private MyList<MyContainer<MyBase>> myList = new MyList<MyContainer<MyBase>>();
public GenericConstraintsTest ()
{
MyContainer<A> ca = new MyContainer<A>(new A());
this.Add<A>(new A());
this.Add<B>(new B());
}
public void Add<S> (S value) where S : MyBase
{
MyContainer<S> cs = new MyContainer<S>(value);
myList.Add(cs);
}
public static void Main()
{
GenericConstraintsTest gct = new GenericConstraintsTest();
}
}
我做错了什么?
干杯
推荐答案
您正试图调用 myList.Add分别具有
因为具有不同通用类型参数的两个通用实例总是不相关的,即使类型参数是相关的,也不能转换为 MyContainer< A>
和 MyContainer< B>
的 MyContainer< MyBase>
。
这样做的唯一方法是创建一个 IMyContainer< out T>
协变通用接口。这将允许您将 IMyContainer< A>
转换为 IMyContainer< MyBase>
if / code>源自
MyBase
。 (注意:只有接口可以有协变和逆变类型参数,这只能在.Net 4中使用。)
The only way to do this is to make an IMyContainer<out T>
covariant generic interface. This will allow you to cast IMyContainer<A>
to IMyContainer<MyBase>
if A
derives from MyBase
. (Note: only interfaces can have covariant and contravariant type parameters, and this is only available in .Net 4).
例如:
public interface IMyContainer<out T> { }
public class MyContainer<T> : IMyContainer<T>
{
public MyContainer(T value) { }
}
public class MyBase { }
public class A : MyBase { }
public class B : MyBase { }
public class GenericConstraintsTest
{
private List<IMyContainer<MyBase>> myList = new List<IMyContainer<MyBase>>();
public GenericConstraintsTest()
{
MyContainer<A> ca = new MyContainer<A>(new A());
this.Add<A>(new A());
this.Add<B>(new B());
}
public void Add<S>(S value) where S : MyBase
{
MyContainer<S> cs = new MyContainer<S>(value);
myList.Add(cs);
}
public static void Main()
{
GenericConstraintsTest gct = new GenericConstraintsTest();
}
}
这篇关于如何管理一个C#泛型类,其类型是基类的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!