Featured post
oop - Need to abstract collections of objects (C#) -
in following simplified example, need abstract collection classes in such way printfruitsandeaters(oranges, orangeeaters); or printfruitsandeaters(apples, appleeaters); becomes possible:
abstract class fruit abstract class fruiteater class apple : fruit class appleeater : fruiteater class orange : fruit class orangeeater : fruiteater class applecollection : list<apple> class orangecollection : list<orange> class appleeatercollection : list<appleeater> class orangeeatercollection : list<orangeeater> i've tried templatizing method , collection classes, need access methods specific fruit , fruiteater classes:
class fruitcollection<t> : list<t> class fruiteatercollection<t> : list<t> void printfruitsandeaters<t, s>(fruitcollection<t> fruits, fruiteatercollection<s> eaters)
then want this:
void printfruitsandeaters<t, s>( fruitcollection<t> fruits, fruiteatercollection<s> eaters) t : fruit s : fruiteater { // ... } this constrain t , s types require; calling method fruitcollection<t>, t cannot guaranteed fruit or subtype, result in compile-time error. same s , fruiteater.
because of constraint, when working value of type t able access members of fruit class, , when working value of type s able access members of fruiteater class.
note that, per brian's (deleted) answer, might want add constraints collection types too:
class fruitcollection<t> : list<t> t : fruit { } class fruiteatercollection<t> : list<t> t : fruiteater { } but this still not allow omit constraints on method.
(also, inheriting list<t> evil thing do, instead use ilist<t>)
- Get link
- X
- Other Apps
Comments
Post a Comment