Convert string to function

0

What is the best way to do a string conversion to void without complications.

I tried to use this code but NullException appears

        private void Mainform_Load(object sender, EventArgs e)
        {   var method = "public void MSG(object o){ MessageBox.Show(o); }";
            method.GetType().GetMethod("MSG").Invoke("MSG", new object[] { "ZZZ" }); //Exception Aqui
        }

But it returns the following:

HomeOnLocation(VS2012)thefollowingappears:

Mycaseisasfollows.Iwanttodevelopalauncherforagame,butthislaunchershouldbedonebasedonSortedDictionary<int,Acion>actionswhereintistheactionidandActionistheactionbasedonastringmethodthatisconvertedtoit.

AndinanXMLwouldbeallthedetailedactions:

<?xml version="1.0" encoding="utf-8" ?> <!-- DO NOT EDIT THIS FILE OR ALL OF THE FUNCTIONS EVEN BECOME INVALID AND UNSTABLE. IN THE CASE MAY RESULT IN SYSTEM FAILURE, AMONG ALL OTHER ERRORS IN COMMON. --> <rels> <rel id="0" exec="play_button" /> <rel id="1" exec="reg_button" /> <rel id="2" exec="home_button" /> <rel id="3" exec="clan_button" /> <rel id="4" exec="shop_button" /> <rel id="5" exec="forum_button" /> </rels>
  

Where rel is declaring the new action, id is the id in int and exec informs the SortedDictionary who should execute the function.

And when he prepares to perform the action:

public async void executar_acao(int id){await Task.Run(lista_de_acoes[id]);
    
asked by anonymous 09.11.2015 / 14:04

1 answer

5

This is the incredibly wrong way to do what you want. You want to define a function at runtime, which is interesting, but it is not by String that you should do this.

The correct thing is to use delegates . The usage is like this:

using System;

public class Program
{
    public delegate void MeuTipoDeDelegate(object o);

    public static void Main()
    {
        MeuTipoDeDelegate teste = delegate(object o) {
            Console.WriteLine(o);
        };

        String umaStringQualquer = "Oi, eu sou uma String";
        teste(umaStringQualquer);
    }
}

I made you a Fiddle by demonstrating this . As in your case you want to define an action dictionary, you can do the following:

public delegate void MinhaAcao(object o);
public SortedDictionary<int, MinhaAcao> dicionarioTeste;

Here you define somewhere in your code the delegate of each action:

MinhaAcao acaoDePlay = delegate(object o) 
{
    /* Escreva aqui a função normalmente */
};

dicionarioTeste.Add(0, acaoDePlay);
    
09.11.2015 / 14:58