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)
需要注意的是,T在IPrimitive<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)
And*_*are 10
我是否也建议(如果你使用的是C#4)你使界面协变?
public interface IPrimitive<out T>
{
T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)
当您需要从列表中取出时,这可以为您节省一些麻烦.