转:反射简单实例
反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。----这是反射最简单的理解。下面就是一个最简答的实例来讲述反射技术的应用!
一. 声明接口,接口中包含一个虚方法。如下
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- public interface IReflect
- {
- void Run(string name);
- }
- }
二. 实现接口,实现接口中的方法。如下
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- public class Reflect:IReflect
- {
- public void Run(string name)
- {
- Console.WriteLine(name+"开始跑了!");
- }
- }
- }
三. 通过反射技术来创建类型的实例,并调用实例的方法。如下
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- IReflect rec = (IReflect)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1.Reflect");
- rec.Run("aaa");
- Console.ReadLine();
- }
- }
- }
这样一个简单的实例就完成了,显示的结果就是“aaa开始跑了”。反射的命名控件是System.Reflection,在使用时候一定要引用该命 名控件,该命名控件长用的对象就是Assembly,该对象包含许多静态方法。其中Load就是很典型的。CreateInstance是用来创建某个对 象的实例。