[英]C# Generics - Classes implementing other generic classes
我有一个
public class A<T> where T : IBase
{
//Does something
}
我需要一个行为类似于A类集合的第二类
public class B<A<T>> : IEnumerable<A<T>> where T : IBase
{
}
问题是我不想创建类似的类
public class B<A<MyCustomObjectP>> : IEnumerable<A<MyCustomObjectP>>
{
}
public class C<A<MyCustomObjectQ>> : IEnumerable<A<MyCustomObjectQ>>
{
}
等等。我想让CustomObject作为实现IBase的通用类型参数。
我发现即使这样做也是非法的:
public class B<T, U> : IEnumerable<T> where T : A<U> where U : IBase
{
}
如果这是非法的,我如何实现这种行为? 有没有更好的设计模式可能会有所帮助?
该IBase
约束被限定在A<T>
所以它必须再次对所有的通用类,希望使用被定义A<U>
使用U
从区分T
在A<T>
类的定义,但它可以被称为任何东西)。 您应该能够简单地做到:
public class B<T> : IEnumerable<A<T>> where T : IBase { ... }
您写道,您需要一个第二类 ,其行为类似于A
类的集合。
由于您还想添加从IBase
继承的其他类(例如B
),因此可以使该集合成为IBase
的集合。
因此,解决方案看起来像这样(请注意,我已经使用List
但是您可以轻松地将其替换为IEnumerable
但随后您必须实现.Add
自己的方法):
void Main()
{
var items = new CollectionOf<IBase>(); // create list of IBase elements
items.Add(new A() { myProperty = "Hello" }); // create object of A and add it to list
items.Add(new B() { myProperty = "World" }); // create object of B and add it to list
foreach(var item in items)
{
Console.WriteLine(item.myProperty);
}
}
// this is the collection class you asked for
public class CollectionOf<U>: List<U>
where U: IBase
{
// collection class enumerating A
// note you could have used IEnumerable instead of List
}
public class A: IBase
{
// class A that implements IBase
public string myProperty { get; set; }
}
public class B: IBase
{
// class B that implements IBase too
public string myProperty { get; set; }
}
public interface IBase {
// some inteface
string myProperty { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.