Reflection(反射)

本文介绍了两个C#反射技术的应用案例。第一个案例展示了如何使用反射动态地为实体类对象赋值;第二个案例则演示了如何通过反射加载DLL文件并调用其中的方法。

反射案例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/archive/2011/08/22/2150022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值