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.
Asked
Active
Viewed 7,760 times
2
-
1What is the question? – Kinetic Jul 14 '16 at 18:44
-
He's asking how to call the method on an object that he typed into the console. So if I type "object.Run()" it will call the Run method on his object. – Jon Jul 14 '16 at 18:47
1 Answers
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
-
-
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
-
-
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
-