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. 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:
- Code a wrapper around
ICollection<T>
that wraps aICollection<IPersistentObject>
and does the type-checking for you. - Use
IEnumerable<T>
instead, which does support variance in the manner you describe. - 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.
精彩评论