使用Reflection动态调用函数

时间:2010-05-10 18:28:49

标签: c# reflection

我正在生成包含以下示例代码的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文件中执行一个对象。 所以,在代码的第二部分(执行部分)中,我只是调用execute函数, 它包含一个函数调用,我在这里命名: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 个答案:

答案 0 :(得分:0)

参数变量是ParameterInfo的数组。因此每个元素都是ParameterInfo类型,而不是相应参数的类型。可以预期您不能将字符串(Text属性的结果类型)强制转换为ParameterInfo。

您需要创建一个与ParameterInfo大小相同的对象数组,并在for循环中构建它。然后,您可以使用MethodInfo实例并使用此对象数组调用Invoke。

答案 1 :(得分:0)

感谢您的回答。 未命名的是setValue,我在这里编写了示例代码:

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

我只想告诉你声明:)

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);
  }
}