明飞的技术园地

笨鸟先飞
  博客园  :: 新随笔  :: 联系 :: 管理

反射应用一 将字符串转换为类名(C#描述)

Posted on 2007-09-18 13:20  明飞  阅读(8435)  评论(2编辑  收藏  举报

 //strHs 传递的函数
//obj传递的函数参数

using System;
using System.Runtime.InteropServices;

 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 public class XHDLL
 {

  public int ADD(int a ,int b)
  {
   return a+b;
  }

  public int MULTIP(int a,int b)
  {
   return a*b;
  }

 }


public string  FunctionCalc(string strHs,object[] obj)
  {
  string strClass ="XHDLL";  //类名

   Type t;
   object o;
   string str="";
   t=Type.GetType(strClass);


//一种方法得到该类下的所有方法然后调用
//   begion
//   System.Reflection.MethodInfo[] methods = t.GetMethods(); //得到所有的方法

//   for(int i=0;i<=methods.Length-1;i++)
//   {
//    if (strHs.ToUpper()==methods[i].Name.ToUpper())
//    {
//      o = System.Activator.CreateInstance(t);
//     str=Convert.ToString(methods[i].Invoke(o,obj));
//    }
//   }
//   end


   //二种方法直接调用
//   begin
   try
   {
    System.Reflection.MethodInfo method=t.GetMethod(strHs.ToUpper());
    o=System.Activator.CreateInstance(t);
    str=Convert.ToString(method.Invoke(o,obj));
   }
 
   catch(Exception ex)
   {
    str=ex.Message;
   }
//   end
   return str.ToString();
  
  }

//调用s

  private void button2_Click(object sender, System.EventArgs e)
  {
  
  object[] obj=new object[]{500,600};
   string str=FunctionCalc("add",obj);
   MessageBox.Show(str);
  }