C#:非泛型类型中的泛型成员?
我有一个包含对象列表的自定义控件。该控件由可视化设计器实例化,然后在代码中配置。该控件是一个显示实体列表的网格。
我有一个这样的初始化方法。
public void Initialise(ISession session, Type type, ICollection<IPersistentObject> objs)
IPersistentObject 是一个接口。但是,当我想分配实现 IPercientObject 的集合时,这不起作用。
所以我把它改成这样。
public void Initialise<T>(ISession session, Type type, ICollection<T> objs) where T : class, IPersistentObject
但现在我想将 objs 参数分配给 ICollection
类型的成员变量,但这是行不通的。
我无法使该类通用,因为它是一个不能具有通用类型的控件。我无法复制集合,因为控件必须修改传入的集合,而不是复制并修改它。
我应该怎么办?
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. However this doesn't work when I want to assign a collection of something that implements 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.
I can't make the class generic because it is a control which can't have generic types 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不需要将对象作为实际的集合(例如使用
Add
/Remove
方法等),那么您可以替换ICollection
与IEnumerable
。If you do not need to the objs to be an actual collection (e.g. with
Add
/Remove
methods etc..) then you could replace theICollection
withIEnumerable
.ICollection
不支持这样的通用方差。在我看来,您的选择是:ICollection
编写一个包装器,该包装器包装ICollection
并为您进行类型检查。IEnumerable
,它确实支持您所描述的方式的差异。IList
,请使用它。ICollection<T>
does not support generic variance like that. As I see it, your options are:ICollection<T>
that wraps aICollection<IPersistentObject>
and does the type-checking for you.IEnumerable<T>
instead, which does support variance in the manner you describe.IList
, if your concrete classes implement it.您可以将成员变量更改为非泛型
ICollection
,并根据需要进行强制转换。You could change the member variable to a non-generic
ICollection
, and cast as appropriate.