1. 反射的学习
A.反射的定义
B.反射举例
namespace Com.Meteor.Interface { public interface IHelper { void Query(); } } namespace Com.Meteor.Dal { public class SqlserverHelper : IHelper { public SqlserverHelper() { Console.WriteLine("这里开始构造SqlserverHelper"); } public void Query() { Console.WriteLine("SqlserverHelper Query"); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Com.Meteor.Interface; using System.Configuration; namespace MyReflection { /// <summary> /// metadata元数据 /// </summary> class Program { static void Main(string[] args) { Console.WriteLine("欢迎大家来流星小子博客,学习反射技术"); // SqlserverHelper sqlserverHelper = new SqlserverHelper(); // sqlserverHelper.Query(); Console.WriteLine("-----------Module--------------"); Assembly assembly = Assembly.Load("Com.Meteor.Dal"); Module[] modules = assembly.GetModules(); foreach (var module in modules) { Console.WriteLine(module.Name); } Console.WriteLine("-----------Type--------------"); Type[] types = assembly.GetTypes(); foreach (var type in types) { Console.WriteLine(type.Name); } Type typeHelper = assembly.GetType("Com.Meteor.Dal.SqlserverHelper"); Object oHelper = Activator.CreateInstance(typeHelper); IHelper iHelper = (IHelper)oHelper; //这句有性能损失,使用了强制类型转换 iHelper.Query();
Console.Read(); } } }
C.注意事项
1.需要把生成的dll放在主程序bindebug目录
如图所示
2.注意 工程添加接口引用