c# - Generics - can I write T based on a variable? -
i'm writing game , have crate class holds item-s of type t varying crate. i've set generics this:
public class crate<i> : item : item { private list<i> contents = new list<i>(); //... }
i'm writing "buy" screen take items, , crates of items delivered. depending on stage player in game, items are/aren't available. hence have list of available items in array.
what want create crates based on array.
for example, array might be
public static list<item> currentlyavailableitems= new list<item>() { new linen(), new food() };
from here, want create buttons generate crates of items. @ moment way can think giant if loop needs updating every time create new items this:
for (int = 0; < gv.currentlyavailableitems.count; i++) { item item = null; if (gv.currentlyavailableitems[i] linen) item = new crate<linen>(); else if (gv.currentlyavailableitems[i] food) item = new crate<food>(); add(new buybutton(item)); }
what want able like:
for (int = 0; < gv.currentlyavailableitems.count; i++) { type t = gv.currentlyavailableitems[i].gettype(); crate<t> crate = new crate<t>(); add(new buybutton(cratetobuy )); }
is possible?
you can reflection:
// todo: consider using foreach loop on gc.currentlyavailableitems type itemtype = gv.currentlyavailableitems[i].gettype(); type cratetype = typeof(crate<>).makegenerictype(t); item crate = (item) activator.createinstance(cratetype); add(new buybutton(crate));
note won't terribly efficient - may enough. if it's not, may want dictionary<type, func<item>>
or that.
c# generics
No comments:
Post a Comment