1

I have a function, that is given a string about which function called it. Is there any way for me to call that function using the string?

void GameLoop()
{ 
  Example("GameLoop")
}

void Example(string functionThatCalledMe)
{
  // Call the method that called this using the string 'functionThatCalledMe'
  Call(functionThatCalledMe);
}

I found a solution at Calling a function from a string in C#, I just don't understand how it works or how to use it. There also appears to be another problem where I cannot use this, so I believe that it is related to that problem.

ugackMiner
  • 31
  • 3

2 Answers2

4

this refers to the instance the code is currently running in.

I think you are probaby adding the this.GetType() to a static method. And a static method is not linked to an instance, so that does not work.

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Works like this:

this.GetType
//or
typeof(ClassName)

Gets the type, which is the class definition you can use at run time.

MethodInfo theMethod = thisType.GetMethod(TheCommandString);

tries to get method definition from type. This can then be used to call (invoke)

theMethod.Invoke(this, userParameters);

Invokes the method definition. But since the method definition does not know to which instance it belongs to, you have to pass an instance, and the parameters you wish to pass. (parameters are not required)

An example would be:

public static void Main()
{
    var test = new Test();

    Type thisType = test.GetType();
    MethodInfo theMethod = thisType.GetMethod("Boop");
    theMethod.Invoke(test , new object[0]);
}

public class Test
{
    public void Boop()
    {
        Console.WriteLine("Boop");
    }
}

Can see the code at:

https://dotnetfiddle.net/67ljft

4

Could this solution solve your problem?

    class Program
    {
        private static Dictionary<string, Action> _myMethods;

        static Program()
        {
            _myMethods = new Dictionary<string, Action>();
            _myMethods.Add("Greet", Greet);
        }

        static void Main(string[] args)
        {

            InvokeMethod("Greet");
            Console.ReadKey();
        }

        private static void InvokeMethod(string methodNameToInvoke)
        {
            _myMethods[methodNameToInvoke].Invoke();
        }

        private static void Greet()
        {
            Console.WriteLine("Hello there!");
        }
    }
denizkanmaz
  • 566
  • 5
  • 9