c# - Instantiating Classes from a Collection of Types -
alright, going take explanation, here goes:
i'm making finite state machine video game states objects derive state base class. since states objects, each has instantiated before becomes current state. each state can have sub-states (which still derive state) can entered , i'm having problem. need able store collection of types of each sub-state. concrete example, here how i'm envisioning working (i realize there bad practices in code, example of goal, not code intend use directly):
public abstract class state { private type[] substates = new type[0]; private state currentstate; public gotosubstate<t> () t : state, new() { if ( substates.contains(t) ) { currentstate = new t(); } } //... } public class stateone : state { public stateone () { substates = new[] { typeof(substatea), typeof(substateb) }; } //... } public class substatea { //... } public class substateb { //... }
now, while more or less works, it's not type safe. since substates
array of type, there's no guarantee derive state. 1 work around use register method can enforce base type @ compile time:
public abstract class state { private list<type> substates = new list<type>; public registersubstate<t> () t : state { substates.add(t); } //... } public class stateone : state { public stateone () { registersubstate<substatea>(); registersubstate<substateb>(); } //... }
but less attractive. there other way accomplish task? ultimately, need able set collection of types, in such way types guaranteed derive state @ compile time.
what have elegant way it. you're getting compiler enforce restriction want, while recording types want.
the alternative store instances of states inside each state. can expose collection containing state
s instead of type
s. maybe isn't amenable application.
Comments
Post a Comment