[英]C#: Generic members in non-generic types?
I have a custom control which contains a list of objects. 我有一个自定义控件,其中包含一个对象列表。 The control is instantiated by the visual designer and then configured in code. 控件由可视化设计器实例化,然后在代码中配置。 The control is a grid which displays a list of entities. 控件是一个显示实体列表的网格。
I have an initialise method like this. 我有这样的初始化方法。
public void Initialise(ISession session, Type type, ICollection<IPersistentObject> objs)
IPersistentObject is an interface. IPersistentObject是一个接口。 However this doesn't work when I want to assign a collection of something that implements IPersistentObject. 但是,当我想分配一个实现IPersistentObject的东西的集合时,这不起作用。
So I changed it to this. 所以我把它改成了这个。
public void Initialise<T>(ISession session, Type type, ICollection<T> objs) where T : class, IPersistentObject
But now I want to assign the objs parameter to a member variable of type ICollection<IPersistentObject>
which doesn't work. 但现在我想将objs参数分配给ICollection<IPersistentObject>
类型的成员变量,该变量不起作用。
I can't make the class generic because it is a control which can't have generic types AFAIK. 我不能使该类通用,因为它是一个不能具有泛型类型AFAIK的控件。 I can't copy the collection because the control MUST modify the passed in collection, not take a copy and modify that. 我无法复制集合,因为控件必须修改传入的集合,而不是复制并修改它。
What should I do? 我该怎么办?
如果你不需要将objs作为一个实际的集合(例如使用Add
/ Remove
方法等),那么你可以用IEnumerable
替换ICollection
。
void Initialise(ISession session, Type type, IEnumerable<IPersistentObject> objs)
ICollection<T>
does not support generic variance like that. ICollection<T>
不支持这样的泛型差异。 As I see it, your options are: 在我看来,你的选择是:
ICollection<T>
that wraps a ICollection<IPersistentObject>
and does the type-checking for you. ICollection<T>
的包装器,它包装ICollection<IPersistentObject>
并为您进行类型检查。 IEnumerable<T>
instead, which does support variance in the manner you describe. 使用IEnumerable<T>
代替,它确实以您描述的方式支持方差。 IList
, if your concrete classes implement it. 如果您的具体类实现它,请使用非泛型IList
。 您可以将成员变量更改为非泛型ICollection
,并根据需要进行ICollection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.