2013-10-13 40 views
1

調用方法下面的代碼是正確找到的類和方法,但它給出了method.Invoke(this, null);正確的語法按名稱

System.Reflection.TargetException was unhandled 
    HResult=-2146232829 
    Message=Object does not match target type. 
    Source=mscorlib 
    StackTrace:..... 

什麼是正確的語法來調用一個void方法下面的錯誤?

using System; 
using System.Reflection; 
using System.Windows; 

namespace ProjectXYZ 
{ 
    class NavigateOptions 
    { 


     public bool runMethod(string debug_selectedClass) 
     { 
      Type t = Type.GetType("ProjectXYZ." + debug_selectedClass); 
      MethodInfo method = t.GetMethod("test"); 
      if (method.IsStatic) 
       method.Invoke(null, null); 
      else 
       method.Invoke(this, null); 

      return true; 

     } 
    } 

    public class Option72 
    { 
     public void test() 
     { 
      string hasItRun = "Yes"; 
     } 
    } 
} 

回答

2

this(類從中調用的方法)是不是在test()方法中定義的類,你就必須提供一個類的一個實例(一個由debug_selectedClass表示)來調用非靜態方法就可以了。

如果它有一個空的構造函數,你可以這樣做:

if (method.IsStatic) 
    method.Invoke(null, null); 
else 
{ 
    object instance = Activator.CreateInstance(t); 
    method.Invoke(instance, null); 
} 
+0

非常感謝。一個快速相關的問題,是否有可能測試類似於'if(method.IsStatic)'的空構造函數,例如'if(method。???)' – user3357963

+0

您可以檢查't.GetConstructor(new Type [0 ])'返回'ConstructorInfo'或'null'。 –

相關問題