How to pick a Function From a string

Asked

Viewed 51 times

-1

I would like to make a system that when informed an integer number (Int) it performs a certain function.

Int Input > Find Object Function > Transform int in a name > executes the function with that name.

Example: It’s not a functional code

public class Main
{
    public static void AcharObjeto(int id)
    {
        for (int Type = 0; Type < Objects.ObjectsList.Length; Type++)
            if (id == Convert.ToInt32(Objects.ObjectsList[Type,1]))
               // Daqui para baixo não funciona e essa e a pergunta!!
               foreach(Obj in Objects)
               {
                   if(Obj.toString() == Objects.ObjectsList[Type,0])
                      Obj();
               }
    }
}

public class Objects
{
   public static string[,] ObjectsList = new string[1, 2] {
        { "Toalha", "1" }
   };

   public static void Toalha()
   {
      Debug.WriteLine("Toalha");
   }
}

I don’t know if you can understand but I’d like to know how to do that! I made this code on market theme like the guy goes there and reads the code, then he has to find it in a code list and assimilate it with the function that makes mark the price or something like that.

An easier way to understand:

string namefunc = "teste";
Main.namefunc();

ANSWERS IN C, PLEASE

2 answers

0


There are a few ways to do this. The most common is to invoke the desired method, picking it up via Reflection.

As shown example, where the class in which the method is found is known, something like:

var funcao = TypeDaclasseOndeEstaOMetodo.GetMethod("NomeDoMetodo");
funcao.Invoke(this, null);

For that it is necessary to do using System.Reflection;.

To catch the class guy, the TypeDaclasseOndeEstaOMetodo, you can do something like var TypeDaclasseOndeEstaOMetodo = this.GetType();, assuming that both methods and where there is invoke are in the same class.

These details may vary depending on your implementation and project organization. Missing more information in the question to present something more detailed.


Edit: According to code presented by AP. Repl: https://repl.it/repls/ImpureBurdensomeDatasets

using System;
using System.Reflection;

class MainClass {
  public static void Main (string[] args) {
    AcharObjeto(1);
  }

  public static void AcharObjeto(int id)
  {
    for (int Type = 0; Type < Objects.ObjectsList.GetLength(0); Type++)
    {
      if (id == Convert.ToInt32(Objects.ObjectsList[Type, 1]))
      {
        var ObjectsType = typeof(Objects);
        var funcao = ObjectsType.GetMethod(Objects.ObjectsList[Type,0]);
        funcao.Invoke(null, null);

        break;
      }
    }
  }
}

public static class Objects
{
   public static string[,] ObjectsList = new string[1, 2] {
        { "Toalha", "1" }
   };

   public static void Toalha()
   {
      Console.WriteLine("Toalha");
   }
}
  • the demonstration code makes it well understand how I would like to do. I can not explain but I will try. I want to call the code Acharobjeto() passing the id of the towel. I want to call the function that is in the class Objectcs.Towel(). I want to do this q the sample codide explains exactly what I want to do. I can’t explain it better. ======== if possible explain better the part of Typedaclasseondeestaometodo because I only have one class and I can’t use this because the code and Static

  • @Zehous, in this case you can do typeof(SuaClasse).

  • @Zehous added logic to his code.

  • ps: also note that you are making incorrect use of the .Length. array I made the correction in the demo.

  • Obg Also Worked.

  • @Zehous in this case may accept the answer and vote in favour

  • yes I just did. ps: (I found out now that this existed)

  • How can I pass int as parameter pq function.Invoke(null, 0); does not work

  • According to the documentation, the 2nd property of Invoke is an array of objects. Therefore, it is necessary to do funcao.Invoke(null, new object[]{ 0 });

Show 4 more comments

0

In the example you wrote you are trying to directly invoke the object when you actually wanted to call a function of it. The following example creates an object through the Activator.Createinstance and then invokes a method named after it. I used the example method you provided:

   public static void AcharObjeto(int id)
{
  for (int Type = 0; Type < Objects.ObjectsList.Length-1; Type++)
    if (id == Convert.ToInt32(Objects.ObjectsList[Type, 1]))
      foreach (var Obj in Objects.ObjectsList)
      {
        if (Obj.ToString() == Objects.ObjectsList[Type, 0])
        {
          var objType = typeof(Objects);
          var funcao = objType.GetMethod(Obj);
          object objectInstance = Activator.CreateInstance(objType, new object[] { });
          funcao.Invoke(objectInstance, null);
        }
      }
}

I ran and it works fine.

   public static void Main() {
    AcharObjeto(1);
   }
  • Obg Yes it worked here too. but I would like to better understand how Activator.CreateInstance. works could help to better understand this command??

  • I left as solution the 1° code. is that he had solved there but I had not understood.

  • is just a more generic way of creating an instance of the object containing the method to be called. To simplify your example you can replace with: function.Invoke(new Objects(), null);

  • obg for trying to help but already solved. obg by the attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.