2016-07-14 147 views
0

假设我有一个带有.Start()方法的对象。 我想通过在控制台中键入方法来调用方法,就像这个“object.Start()”,它应该调用.Start()方法。用字符串对象调用方法

+1

什么问题? – Kinetic

+0

他问如何调用他输入到控制台的对象的方法。所以如果我输入“object.Run()”,它会调用他的对象的Run方法。 – Mangist

回答

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

我可以使用参数吗? –

+0

是的,在methodInfo.Invoke()而不是为第二个参数传递'null',您可以传递方法参数的对象数组。所以如果你想通过“ABC”和123,你可以用methodInfo.Invoke(obj,new object [] {“ABC”,123})来调用它。 – Mangist

+0

啊谢谢。和obj中的“obj.GetType();”是包含该方法的对象吗? –