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.
-
1What is the question?Kinetic– Kinetic2016-07-14 18:44:46 +00:00Commented Jul 14, 2016 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– Jon2016-07-14 18:47:59 +00:00Commented Jul 14, 2016 at 18:47
Add a comment
|
1 Answer
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);
}
}
7 Comments
Samks
Can I use parameters with it?
Jon
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 });
Samks
Ah thanks. And obj in " obj.GetType();" is the object that contains the method?
Jon
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
@SamuelKlit if its working for you, can you mark it as the answer?
|