通用接口的通用列表不允许,还有其他方法吗? [英] Generic List of Generic Interfaces not allowed, any alternative approaches?
本文介绍了通用接口的通用列表不允许,还有其他方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到正确的方式来使用通用接口的通用列表作为变量。
I am trying to find the right way to use a Generic List of Generic Interfaces as a variable.
这里是一个例子。这可能不是最好的,但希望你能明白这一点:
Here is an example. It is probably not the best, but hopefully you will get the point:
public interface IPrimitive<T>
{
T Value { get; }
}
然后在另一个类中,我希望能够声明一个变量它包含任意 T
的实现 IPrimitive< T>
的对象列表。
and then in another class, I want to be able to declare a variable that holds a list of objects that implement IPrimitive<T>
for arbitrary T
.
// I know this line will not compile because I do not define T
List<IPrimitive<T>> primitives = new List<IPrimitives<T>>;
primitives.Add(new Star()); // Assuming Star implements IPrimitive<X>
primitives.Add(new Sun()); // Assuming Sun implements IPrimitive<Y>
注意 T
在 IPrimitive< T>
对于列表中的每个条目都可能不同。
Note that the T
in IPrimitive<T>
could be different for each entry in the list.
关于如何设置这种关系的任何想法?替代方法?
Any ideas on how I could setup such a relationship? Alternative Approaches?
推荐答案
public interface IPrimitive
{
}
public interface IPrimitive<T> : IPrimitive
{
T Value { get; }
}
public class Star : IPrimitive<T> //must declare T here
{
}
然后您应该可以拥有
List<IPrimitive> primitives = new List<IPrimitive>;
primitives.Add(new Star()); // Assuming Star implements IPrimitive
primitives.Add(new Sun()); // Assuming Sun implements IPrimitive
这篇关于通用接口的通用列表不允许,还有其他方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文