Reflection(反射)

反射案例1:

DataRow dr = DAL.GetDataRow();   //从数据库取得一条记录
            Employee e =new Employee();//实例化一个对象(可以为实体)
            System.Reflection.PropertyInfo[] ps = e.GetType().GetProperties();//取得对象的所有属性
            foreach(System.Reflection.PropertyInfo p in ps)
            {
                p.SetValue(e, Convert.ChangeType(dr[p.Name], p.PropertyType),
null);//循环附值      
            }

这样写代码简洁,但数据库结构变化只要改实体类代码就好,
类似这种,还可以动态执行方法

反射案例2:

1)生产一个DLL文件

C# code

using System;
using System.Collections.Generic;
using System.Text;
 namespace text
{
publicclass zhj
 {
   publicvoid Fun()
   {
     Console.WriteLine("sdsf");
   }
}
}
2)利用反射技术访问上面生产的DLL文件

C# code

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
 {
class Program
{
staticvoid Main(string[] args)
 {
  Assembly ass = Assembly.LoadFrom("E:\\text.dll");//获取程序集
  object obj = ass.CreateInstance("text.zhj"); //获取实例
  Type mytype = ass.GetType("text.zhj"); //获取类型
  MethodInfo meth = mytype.GetMethod("Fun"); //获取方法
  meth.Invoke(obj, null);
}
}
}






 

原文地址:https://www.cnblogs.com/cntom/p/2150022.html