2011-08-25 183 views
2

我有以下的方法,通過胃腸 delared:Get方法失敗

public static void Get(int pname, out int @params) 

我試圖讓使用下列方式反映它:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", 
              BindingFlags.Public|BindingFlags.Static, 
              null, 
              new Type[] 
              { 
               typeof(Int32), 
               typeof(Int32) 
              }, 
              null); 

但是我有沒有成功。爲什麼?

是否因爲關鍵字?

+0

你使用.NET 4嗎?如果是這樣,您可以使用動態關鍵字來創建反射對象,然後直接調用該方法。這樣你就不需要MethodInfo查找。缺點是,如果你弄錯了,你會得到一個運行時異常 – ghostJago

回答

7

使用typeof(Int32).MakeByRefType()你的第二個參數。即:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", bindingFlags.Public|BindingFlags.Static, null, new Type[] { typeof(Int32), typeof(Int32).MakeByRefType() }, null); 
+0

它已經工作了,但是如何在方法調用中處理它呢? – Luca

+0

找到它了:http://stackoverflow.com/questions/2438065/c-reflection-how-can-i-invoke-a-method-with-an-out-parameter – Luca

0

如何嘗試這樣的事情,而不是:

MethodInfo method = this.GetType().GetMethod("Get"); 
if (method != null) 
{ 
    method.Invoke(this, new object[] { "Arg1", "Arg2", "Arg3" }); 
} 
1

如果需要指定該方法的具體超載話,肯定有什麼@Isaac Overacker說去。否則,只是不指定參數:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", BindingFlags.Public | BindingFlags.Static); 
1

out關鍵字經過參考的參數,這可能是你的問題。您需要將其標記爲引用類型,因爲C#允許您使用byValue和byReference參數來重載方法。