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

时间:2016-07-14 18:43:40

标签: c# reflection system.reflection

假设我有一个对象,使用.Start()方法。 我想通过在控制台中输入来调用该方法,就像调用.Start()方法的“object.Start()”一样。

1 个答案:

答案 0 :(得分:1)

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