使用字符串调用对象中的方法

Call method in object with string

假设我有一个带有 .Start() 方法的对象。 我想通过在控制台中键入来调用该方法,例如 "object.Start()",应该调用 .Start() 方法。

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);
    }
}