通用接口的通用列表不允许,任何替代方法?

P B*_*P B 24 c# generics interface generic-list

我试图找到使用通用接口通用列表作为变量的正确方法.

这是一个例子.这可能不是最好的,但希望你能明白这一点:

public interface IPrimitive<T>
{
     T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)

然后在另一个类中,我希望能够声明一个包含实现IPrimitive<T>任意对象的列表的变量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>
Run Code Online (Sandbox Code Playgroud)

需要注意的是,TIPrimitive<T>可能是列表中的每个条目不同.

关于如何建立这种关系的任何想法?替代方法?

Jos*_*osh 25

public interface IPrimitive
{

}

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

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

}
Run Code Online (Sandbox Code Playgroud)

然后你应该能够拥有

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

primitives.Add(new Star());   // Assuming Star implements IPrimitive
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive
Run Code Online (Sandbox Code Playgroud)

  • 但是......但......太阳是一颗星! (6认同)
  • 通过使用IPrimitive列表而不是IPrimitive <T>将不允许您从列表中的项获取值,因为Value在IPrimitive <T>中定义而不是IPrimitive. (3认同)
  • @PB,使用这种方法,`IPrimitive`将有一个属性定义为`object Value {get; 然后``Star`需要提供`IPrimitive <T>`和`IPrimitive`的实现.如:`public int Value {get {return _value; 实现`IPrimitive <int>`和`对象IPrimitive.Value {get {return this.Value; `明确地处理非泛型接口. (2认同)

And*_*are 10

约翰是对的.

我是否也建议(如果你使用的是C#4)你使界面协变?

public interface IPrimitive<out T>
{
     T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)

当您需要从列表中取出时,这可以为您节省一些麻烦.