我试图找到使用通用接口通用列表作为变量的正确方法.
这是一个例子.这可能不是最好的,但希望你能明白这一点:
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>可能是列表中的每个条目不同.
关于如何建立这种关系的任何想法?替代方法?