.NET反射Reflection机制学习

来源:互联网 发布:ubuntu qt环境搭建 编辑:程序博客网 时间:2024/05/21 17:08

口说无凭,示例为证。先看个小例子吧~~

先作成一个类,用于Reflection调用。

using System;namespace ReflectionTest{    public class Car    {        private string _engin1;        private string _engin2;        public string Engin1        {            get { return _engin1; }            set { this._engin1 = value; }        }        public string Engin2        {            get { return _engin2; }            set { _engin2 = value; }        }        public String GetCar()        {            return "I am a car";        }    }}

通过VS2010建立一个WinForm项目,在Form窗体中加入两个TextBox,双击Form窗体,在Form1_Load中进行编码,源码如下:

using System;using System.Reflection;using System.Windows.Forms;namespace ReflectionTest{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            //通过Assembly类来Reflection对象            Assembly assembly = Assembly.Load("ReflectionTest");            //通过Assembly创建对象实例,并强制转换为Car对象类型            Car car1 = (Car)assembly.CreateInstance("ReflectionTest.Car");            //将GetCar()方法返回值赋给文本框            this.textBox1.Text = car1.GetCar();            //从配置文件中读取Reflection对象名            string objString = System.Configuration.ConfigurationManager.AppSettings["car"];            //通过Assembly类获取对象的Type            Type type = assembly.GetType(objString);            //通过Activator对象创建对象实例,并强制转换为Car对象类型            Car car2 = (Car)Activator.CreateInstance(type);            //将GetCar()方法返回值赋给文本框            this.textBox2.Text = car2.GetCar();        }    }}

配置文件示例代码如下:

<?xml version="1.0" encoding="utf-8" ?><configuration>  <appSettings>    <add key="car" value="ReflectionTest.Car"/>  </appSettings></configuration>







0 0