how to execute a method from user input

  • Thread starter Thread starter L.Peter
  • Start date Start date
L

L.Peter

Dear Group,
i have a combobox and a button on a form.
the combobox has three values: stop, pause,start
when user press the button, the program will take apropriate action
at the momment, here is what i did
switch (choice)
{
case start: objGame.start
case stop: objGame.stop
case pause: objGame.pause
}

what i really want to be able to do is : (as methods may expand in the
future like restart, ...)
doaction(userchoice)

void doaction(string userchoice)
{
string str = "objGame."+userchoice;
//How to this
run str
}

TIA
L.Peter
 
what you can do is
1) push the case statement into your objGame object
public void objGame.DoAction( SomeEnum choice)
{
switch(choise)
{
case SomeEnum.Start:
this.Start;
...
}

2) or, if you really, really, really want to do this, use reflection. It is
slow and overkill for this, but you can do it:

objGame.GetType().InvokeMember( choice.ToString(), BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.Instance, null, objGame, new object[]
{});
 
Hi Philip,
I go with your first suggestion

Thank you very much

Regards

Peter

Philip Rieck said:
what you can do is
1) push the case statement into your objGame object
public void objGame.DoAction( SomeEnum choice)
{
switch(choise)
{
case SomeEnum.Start:
this.Start;
...
}

2) or, if you really, really, really want to do this, use reflection. It is
slow and overkill for this, but you can do it:

objGame.GetType().InvokeMember( choice.ToString(), BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.Instance, null, objGame, new object[]
{});



L.Peter said:
Dear Group,
i have a combobox and a button on a form.
the combobox has three values: stop, pause,start
when user press the button, the program will take apropriate action
at the momment, here is what i did
switch (choice)
{
case start: objGame.start
case stop: objGame.stop
case pause: objGame.pause
}

what i really want to be able to do is : (as methods may expand in the
future like restart, ...)
doaction(userchoice)

void doaction(string userchoice)
{
string str = "objGame."+userchoice;
//How to this
run str
}

TIA
L.Peter
 
Back
Top