-1

I wanna have a method that gives a string as other method name and param array of object, then call that other method and gives param to its arguments how can I do that

example :

public void callMethod(string methodName,params object[] args)
{
    //call other method by name
}

and other methods :

public void methodOne(int i, float f)
{

}
public void methodTwo(string r)
{

}
  • 1
    You might want to look at https://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp – Progman May 02 '20 at 14:53
  • How do `args` and those function calls relate? is `args` supposed to contain, what you call those other functions with. If you could limit it to one type at a time, you could use generics. If you could limit it down to one function at a time, you could use a Enumeration rather then a name to identify the function. Reflection is a powerfull fallback tool, but it should not be overused. | Overall it sounds like a XY problem - there is very likely a better way to solve your issues then this. – Christopher May 02 '20 at 14:56
  • @Peyman Ansary: If you don't have type or instance of class which has that method, in "CallMethod", it won't work. I would suggest passing Action in CallMethod rather than passing string of method name. – A.Learn May 02 '20 at 15:25
  • im writing a plugin for unity . so i don't know the other method gonna call what would be – Peyman Ansary May 02 '20 at 17:03

1 Answers1

2

As Progman suggested in the comments, you can do it like this.

private void Test()
{
    object[] args1 = new object[] { 2, (float)5.6 };
    callMethod("methodOne", args1);
    object[] args2 = new object[] { "Hello" };
    callMethod("methodTwo", args2);
}

public void callMethod(string methodName, params object[] args)
{
    Type thisType = this.GetType();
    System.Reflection.MethodInfo theMethod = thisType.GetMethod(methodName);
    theMethod.Invoke(this, args);
}

public void methodOne(int i, float f)
{
    Console.WriteLine("first:" + i + " second:" + f);
}

public void methodTwo(string r)
{
    Console.WriteLine(r);
}
Armin
  • 576
  • 6
  • 13