c# - Generic collection in generic class -
i have custom class (let's call myclass
) looks this:
public class myclass { private list<myclass> list; private object data; }
however, want rid of object
property , instead use generic class. this:
public class myclass<t> { private list<myclass<t>> list; private t data; }
however, in need behavior:
myclass<foo> foo = new myclass<foo>; foo.list = new list<myclass<bar>>;
so need able have different datatypes foo-instance , list/data-property in foo. t's in generic example same , allow this:
myclass<foo> foo = new myclass<foo>; foo.list = new list<myclass<foo>>;
each item in foo.list again have list might of different type. time compile myclass
have no knowledge datatypes in lists/data-property or how many levels there be. how can build flexible structure?
generics designed allow compiler perform checks on type usage , provide nifty additional benefits.
what you've described cannot achieved generics, if each time you're updating list
list of potentially different type generics cannot you.
however, if each of these types share common base type or share common interface use t
list , allow use them.
if each instance of myclass
allows 1 type of list of myclass<?>
revise myclass
such:
public class myclass<t, tlist> { private list<myclass<t, tlist>> list; private t data; }
Comments
Post a Comment