2016-07-14 80 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();」是包含該方法的對象嗎? –