2010-05-10 63 views
1

我生成DLL文件包含如以下示例代碼:調用函數動態通過使用反射

using System; 
using System.Collections; 
using System.Xml; 
using System.IO; 
using System.Windows.Forms; 

namespace CSharpScripter 
{ 

public class TestClass : CSharpScripter.Command 
{ 
    private int i=1; 
    private int j=2; 
    public int k=3; 

    public TestClass6() 
    { 

    } 

    public void display (int i,int j,int k) 
    { 
     string a = null; 
     a= k.ToString(); 

     string a1 = null; 
     a1= this.i.ToString(); 

     string a2 = null; 
     a2= j.ToString(); 

     MessageBox.Show(" working! "+ "k="+ a +" i="+a1 + " j="+ a2); 
    } 

    public void setValues(int i,int j,int k1) 
    { 
     this.i=i; 
     this.j=j; 
     k=k1; 
    } 

我編譯前面的代碼,然後我從DLL文件執行的對象。 因此,在代碼的第二部分(執行部分),我只是調用執行功能, 它包含一個函數調用,我在這裏命名爲:display。

爲此,我需要通過setValue函數在聲明中設置值。 我希望它是動態的(setValues方法)調用,它具有類似的聲明:

public void(Parameter[] parameters) 
{ 
    //some code block here 
} 

對於這種情況,我用思考。

Type objectType = testClass.GetType(); 
MethodInfo members = objectType.GetMethod("setValues"); 

ParameterInfo[] parameters = members.GetParameters(); 

for(int t = 0; t < parameters.Length; t++) 
{ 
    if (parameters[t]. ParameterType == typeof()) 
    { 
      object value = this.textBox2.Text; 
      parameters.SetValue(Convert.ChangeType(value,parameters[t].ParameterType), t);          
    } 
} 

但它會拋出一個轉換錯誤「對象不能存儲在這種類型的數組中」。在最後一行,在(setValue)方法的第一個參數中。 這裏有什麼問題?

如何在前面的代碼之後動態調用方法(Invoke)還是有更好的方法?

謝謝。

+2

請檢查您的格式:)。將代碼放入代碼塊中。 – Simon 2010-05-10 18:33:41

+0

是的,我試圖做到這一點,但它仍然不完全合理。@Alaa',這個以參數數組爲參數的未命名函數是什麼? – Timores 2010-05-10 18:50:14

回答

0

參數變量是一個ParameterInfo數組。因此,每個元素的類型都是ParameterInfo,而不是相應參數的類型。預計您不能將字符串(Text屬性的結果類型)轉換爲ParameterInfo。

您需要創建一個與ParameterInfo大小相同的對象數組,並將其構建到for循環中。然後,您可以使用MethodInfo實例並使用此對象數組調用Invoke。

0

感謝您的回答。 未命名是的setValue,我寫的示例代碼在這裏:

公共無效setValues方法(INT I,詮釋J,INT K1) { this.i I =; this.j = j; k = k1; }

我只是想告訴你的聲明:)

公共無效(參數[]參數) {// 一些代碼塊在這裏 }

無論如何,我們不能忘記這部分的未命名函數,只關注此代碼:

類型objectType = testClass.GetType();
MethodInfo members = objectType.GetMethod(「setValues」); ParameterInfo [] parameters = members.GetParameters();對於(int t = 0; t < parameters.Length; t ++) { If(parameters [t]。ParameterType == typeof()) { object value = this.textBox2.Text;參數SetValue(Convert.ChangeType(value,parameters [t] .ParameterType),t);}}

+0

我同意專注於其餘部分(儘管您不應該將人們與不相關的代碼混淆)。請看上面我的答案的第二部分。 – Timores 2010-05-10 22:31:13