大家看这个问题怎么解决:有一个函数
foo(int a)
在调用前我只知道函数名和参数个数,但不知道参数类型,但在另外一个地方知道参数类型的 System.String和参数的值,如
<a DataType="System.Int32" value="12345" />
这些类型都提供了一个转换函数Parse(string),把当前的字符串转换成设定类型的值,然后作为参数供foo调用
函数模型如下:object CallFunc(funcName,paraDataType,paraValue)例如 CallFunc("System.Math.Sqrt",new object[]{"System.Double","123.456"}) 返回 123.456的平方根如何完成代码编写呢

解决方案 »

  1.   

    或者对已知对象的动态属性赋值foo( object obj,string attName,string attValue)例如:
    DropDownList d;
    ..
    foo( d,"SelectedIndex","12")//设置d的第十二项为选中项System.Windows.Forms.DateTimePicker p;
    ..
    foo(p,"Value","2007-8-8 08:12:24");//设置p的当前值System.Windows.Forms.TextBox t;
    ..
    //选中TextBox控件t的第2到第14个字符
    foo(t,"Select",new object[]{"System.Int32","1","System.Int32","13"});
      

  2.   

    1public void test1()
     2  {
     3   System.Reflection.Assembly ass;
     4   Type type ;
     5   object obj;
     6   try
     7   {
     8    ass = System.Reflection.Assembly.LoadFile(@"d:\TestReflect.dll");
     9    type = ass.GetType("Webtest.ReflectTest");//必须使用名称空间+类名称
    10    System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
    11    obj = ass.CreateInstance("Webtest.ReflectTest");//必须使用名称空间+类名称
    12    string s = (string)method.Invoke(obj,new string[]{"jianglijun"}); //实例方法的调用
    13   
    14    Response.Write(s+"<br>");
    15    method = type.GetMethod("WriteName");//方法的名称
    16    s = (string)method.Invoke(null,new string[]{"jianglijun"}); //静态方法的调用
    17    Response.Write(s+"<br>");
    18
    19    method = type.GetMethod("WriteNoPara");//无参数的实例方法
    20    s = (string)method.Invoke(obj,null);
    21    Response.Write(s+"<br>");
    22    method = null;
    23   }
    24   catch(Exception ex)
    25   {
    26    Response.Write(ex+"<br>");
    27   }
    28   finally
    29   {
    30    ass = null;
    31    type = null;
    32    obj = null;
    33   }
    34  }
      

  3.   

    bitsbird(一瓢 在路上...) 
    这种方式不错,可是现在不知道调用函数的参数类型,而您给的事例是事前知道参数类型的
    在您的16行s = (string)method.Invoke(null,new string[]{"jianglijun"}); //静态方法的调用
    new string[]{"jianglijun"}就是事先知道参数是一个string类型的变量
      

  4.   

    Type theMathType=Type.GetType("System.Math");
    Type[] parameterTypes=new Type[1];
    parameterTypes[0]=Type.GetType("System.Double");
    MethodInfo CosinInfo=theMathType.GetMethod("Cos",parameterTypes); 
    Object[] parameters=new Object[1];
    parameters[0]=45;
    Object result=CosinInfo.Invoke(null,parameters);
    Console.WriteLine(result.ToString());
      

  5.   

    Convert.ChangeType(paraValue,paraDataType)老天保佑给你的字符串能转化成功吧,阿门。