Generic List of Generic Interfaces not allowed, any alternative approaches?

青春壹個敷衍的年華 提交于 2019-12-03 08:26:15

问题


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; }
}

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>

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?


回答1:


public interface IPrimitive
{

}

public interface IPrimitive<T> : IPrimitive
{
     T Value { get; }
}

public class Star : IPrimitive<T> //must declare T here
{

}

Then you should be able to have

List<IPrimitive> primitives = new List<IPrimitive>;

primitives.Add(new Star());   // Assuming Star implements IPrimitive
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive



回答2:


John is correct.

Might I also suggest (if you are using C# 4) that you make your interface covariant?

public interface IPrimitive<out T>
{
     T Value { get; }
}

This could save you some trouble later when you need to get things out of the list.




回答3:


You say it won't work because you don't define T. So define it:

public class Holder<T>
{
    public List<IPrimitive<T>> Primitives {get;set;}
}


来源:https://stackoverflow.com/questions/4522580/generic-list-of-generic-interfaces-not-allowed-any-alternative-approaches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!