netInfo

学习的最好方式就是写下来,不积跬步,无以致千里

博客园 首页 新随笔 联系 订阅 管理

学习反射后的一些心得

1.       什么是反射

可以理解为动态的发现类的信息

2.       反射可以获得成员信息等,还可以访问变量,如private变量

反射的层次模型

3.       反射的作用

可以获得Assembly中的资源

4.       使用反射动态绑定有性能的损耗

5.       一个例子

一个*.cs文件,编译成TestReflection .dll

 

using System;

using System.Windows.Forms;

 

public class TestReflection {

 

   public static double AddTwoDoubles(double num1, double num2){

      return num1 + num2;

   }

 

   public DialogResult ShowMessage(String message){

      return MessageBox.Show(message);

   }

}

  

新建一个winform工程,编译后将TestReflection .dllexe文件放在同一目录下。

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Reflection;

using System.Reflection.Emit;

using System.IO;

using System.Text;

using System.Threading;

 

namespace WindowsApplication1

{

     /// <summary>

     /// Form1 的摘要说明。

     /// </summary>

     public class Form1 : System.Windows.Forms.Form

     {

         private System.Windows.Forms.Button button1;

         private System.Windows.Forms.TextBox textBox1;

         private System.Windows.Forms.ListBox listBox1;

 

省略了

         private void button1_Click(object sender, System.EventArgs e)

         {

              Assembly assembly;

              Type type;

              try

              {

                   assembly=Assembly.LoadFrom("TestReflection.dll");

                   type=assembly.GetType("TestReflection");

              }

              catch(FileNotFoundException)

              {

                   textBox1.Text="Cound not load Assembly";

                   return;

              }

              catch(TypeLoadException)

              {

                   textBox1.Text="Cound not load Type";

                   return;

              }

             

 

              String[] args = new string[1];

              args[0]="hello world";

             

              Object instance = null;

              instance = Activator.CreateInstance(type);

             

              MethodInfo[] mm=type.GetMethods();

              foreach(MethodInfo m in mm)

              {

                   listBox1.Items.Add(m.Name);

 

                   if (m.Name=="ShowMessage")

                   {

                       m.Invoke(instance,args);                      

                   }

              }

         }

     }

}

posted on 2005-01-02 23:08  边城浪子  阅读(565)  评论(0编辑  收藏  举报