![](/img/trans.png)
[英]Using Generics in Base Classes in C#: How to ensure methods in the base class return the derived class's type?
[英]How do you manage a C# Generics class where the type is a container of a base class?
我收到以下错误
`System.Collections.Generic.List>.Add(MyContainer)' 的最佳重载方法匹配有一些无效的 arguments (CS1502) (GenericsTest)
对于以下 class:
A 和 B 是 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();
}
}
我究竟做错了什么?
干杯
您正在尝试分别使用MyContainer<A>
和MyContainer<B>
调用myList.Add
。 两者都不能转换为MyContainer<MyBase>
因为具有不同泛型类型参数的两个泛型实例总是不相关的,即使类型参数是相关的。
做到这一点的唯一方法是创建一个IMyContainer<out T>
协变通用接口。 如果A
从MyBase
派生,这将允许您将IMyContainer<A>
转换为IMyContainer<MyBase>
。 (注意:只有接口可以有协变和逆变类型参数,这仅在.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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.