2

Let's say I have a object, with a .Start() method. I want to call the method by typing in the console, like this "object.Start()", that should call the .Start() method.

Samks
  • 96
  • 1
  • 10

1 Answers1

4
class Program
{
    static void Main(string[] args)
    {
        var obj = new object(); // Replace here with your object 

        // Parse the method name to call
        var command = Console.ReadLine();
        var methodName = command.Substring(command.LastIndexOf('.')+1).Replace("(", "").Replace(")", "");

        // Use reflection to get the Method
        var type = obj.GetType();
        var methodInfo = type.GetMethod(methodName);

        // Invoke the method here
        methodInfo.Invoke(obj, null);
    }
}
Jon
  • 3,230
  • 1
  • 16
  • 28
  • Can I use parameters with it? – Samks Jul 14 '16 at 18:50
  • Yes, on the methodInfo.Invoke() instead of passing 'null' for the 2nd parameter, you can pass an object array of the method parameters. So if you want to pass "ABC", and 123, you can call it with methodInfo.Invoke(obj, new object[] { "ABC", 123 }); – Jon Jul 14 '16 at 18:51
  • Ah thanks. And obj in " obj.GetType();" is the object that contains the method? – Samks Jul 14 '16 at 18:52
  • obj should be your object that you want to call the method on, yeah. Instead of "var obj = new object();" you should replace that with your own object, wherever you're getting it from. – Jon Jul 14 '16 at 18:54
  • @SamuelKlit if its working for you, can you mark it as the answer? – Jon Jul 14 '16 at 18:56
  • obj.GetType() will give you the Type. That is the class info you need. What else are you looking for? – Jon Jul 14 '16 at 19:05
  • Nevermind. I figured it out. – Samks Jul 14 '16 at 19:06