c# - "Covariance" in template parameters -
let's have these 2 classes
class baseclass { protected hashset<baseclass> container; } class derivedclass : baseclass { derivedclass() { container = new hashset<derivedclass>(); } }
then receive error: unable convert.
since every derivedclass (should) baseclass, i'm not quite sure why error being thrown, yet is.
the goal baseclass perform variety of operations on container
, particularly specific behaviors tied derivedclass - among those, requiring container of type hashset<derivedclass>
.
how goal accomplished?
every devrivedclass
baseclass
, not other way around. hashset<t>
cannot covariant since allows write operations (add
). in scenario possible:
class baseclass { protected hashset<baseclass> container; public dosomething() { container.add(new baseclass()); // not legal if container list<derivedclass> } }
you change type of container covariant:
class baseclass { protected ienumerable<baseclass> container; } class derivedclass : baseclass { derivedclass() { container = new hashset<derivedclass>(); } }
but derives class(es) add items container
(which may work in design).
you try making base class generic:
class baseclass<t> t:baseclass<t> { protected hashset<t> container; } class derivedclass : baseclass<derivedclass> { derivedclass() { container = new hashset<derivedclass>(); } }
which looks little strange, again looks strange class contain list of objects of same type, maybe in real scenario makes sense.
Comments
Post a Comment