转:反射简单实例

反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。----这是反射最简单的理解。下面就是一个最简答的实例来讲述反射技术的应用!

 

一. 声明接口,接口中包含一个虚方法。如下

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication1  
  7. {  
  8.     public interface IReflect  
  9.     {  
  10.         void Run(string name);  
  11.     }  
  12. }  

 

二.  实现接口,实现接口中的方法。如下

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication1  
  7. {  
  8.     public class Reflect:IReflect  
  9.     {  
  10.         public void Run(string name)  
  11.         {  
  12.             Console.WriteLine(name+"开始跑了!");  
  13.         }  
  14.     }  
  15. }  

 

三. 通过反射技术来创建类型的实例,并调用实例的方法。如下

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Reflection;  
  6.   
  7. namespace ConsoleApplication1  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             IReflect rec = (IReflect)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1.Reflect");  
  14.             rec.Run("aaa");  
  15.             Console.ReadLine();  
  16.         }  
  17.     }  
  18. }  
 

 

这样一个简单的实例就完成了,显示的结果就是“aaa开始跑了”。反射的命名控件是System.Reflection,在使用时候一定要引用该命 名控件,该命名控件长用的对象就是Assembly,该对象包含许多静态方法。其中Load就是很典型的。CreateInstance是用来创建某个对 象的实例。

posted @ 2011-11-07 16:11  追_bk  阅读(179)  评论(0编辑  收藏  举报