Main Site Documentation

Get Code from String


#1

Hello Guys,
I’m working on an Menu for the N18 Display and i have a problem.
I have all the different Menu positions already in a String. And every position has it’s own method, so i need to get the text from the string and convert it to code.
Lets say:


string MenuPos1 = "MenuPos1";
string s = "();";
MenuPos1 = MenusPos1 + s;

So now the string looks like “MenuPos1();” and i now want to call this method. But i need this String in code.


void MenuPos1()
{
}

I could make a query for ever position, but i want like 20 Sub menus. So it would be way too much.

Thanks in advance
Benjamin


#2

You can use reflection.


#3

In my perspective this is superior programming (the last thing i programmed was a calculator;) ).
Would it be possible to make an example oriented by my given code?


#4

@ -Encore- - You could do something like this:


// call this method with the name of the selected menu position
public void ExecuteMenu(string menuPos)
{
     switch (menuPos)
     {
          case "MenuPos1":
               DoMenuPos1();
                break;
          case "MenuPos2":
               DoMenuPos2();
                break;
          case "MenuPos3":
               DoMenuPos3();
                break;
     }
}

private void DoMenuPos1()
{
     // do menu position 1 stuff here...
}

private void DoMenuPos2()
{
     // do menu position 2 stuff here...
}

private void DoMenuPos3()
{
     // do menu position 3 stuff here...
}

#5

This was my idea first, but i would need to do a very long list for every position. I thoght there was an more elegant way to do it.


#6

Yes, I agree. A more elegant way would be to use delegates. Each DoMenuPosN method would be added to a dictionary with the “MenuPosN” as the key.

See this post by @ Architect:

https://www.ghielectronics.com/community/forum/topic?id=2080&page=1#msg21141


#7

Hmm… i would need to rebuild the whole program. Im just going to look into reflections.
Thanks anyway.


#8

So i looked into it and partly understood it, but if i want to try it in my program I get an error.
The Type or Namespacename “MethodInfo” couldnt be found.

 
Method = MenuP[selecteditem - 1];

MethodInfo mi = this.GetType().GetMethod(Method);

mi.Invoke(this, null);


#9

Ah got it needed to add the System.Reflection namespace


#10

Got another Error: Error invoking method “Gadgeteer.Interfaces.InterruptInput” (check arguments to Program.BeginInvoke are correct)

with this code:


            MethodInfo mi = this.GetType().GetMethod(MenuP[selecteditem - 1]);

            mi.Invoke(this, null);

Anyone have an idea what ths solution could be ?

EDIT: I forgot to put public in front of the Method
I got it now working.


#11

Reflection is very neat feature and not as complicated as you have already figured out. Glad you got it working.