我生成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)還是有更好的方法?
謝謝。
請檢查您的格式:)。將代碼放入代碼塊中。 – Simon 2010-05-10 18:33:41
是的,我試圖做到這一點,但它仍然不完全合理。@Alaa',這個以參數數組爲參數的未命名函數是什麼? – Timores 2010-05-10 18:50:14