开发者

C#: Generic members in non-generic types?

开发者 https://www.devze.com 2023-01-20 15:15 出处:网络
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 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 IC开发者_运维百科ollection<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?


If you do not need to the objs to be an actual collection (e.g. with Add/Remove methods etc..) then you could replace the ICollection with IEnumerable.

void Initialise(ISession session, Type type, IEnumerable<IPersistentObject> objs)


ICollection<T> does not support generic variance like that. As I see it, your options are:

  1. Code a wrapper around ICollection<T> that wraps a ICollection<IPersistentObject> and does the type-checking for you.
  2. Use IEnumerable<T> instead, which does support variance in the manner you describe.
  3. Use the non-generic IList, if your concrete classes implement it.


You could change the member variable to a non-generic ICollection, and cast as appropriate.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号