标签:
反射的基本概念: .Net Framework 中提供了反射机制,可以再加载程序运行时,动态获取和加载程序集,并且可以获取到程序集的信息
创建Assembly和Entity两个程序集,在Assembly中添加Entity引用,如下图:
namespace Entity { public class GetData { public static SIMPEntities SIMP = new SIMPEntities(); /// <summary> /// 查询方法--返回序列化json /// </summary> /// <returns></returns> public string GetResule() { JavaScriptSerializer Serialize = new JavaScriptSerializer(); var list = SIMP.Sys_Employee .Select(a => new { id = a.EmpId, EmpName = a.EmpName, PositionName = (a.Sys_Position!=null)?a.Sys_Position.PositionName:"无" }) .ToList(); return Serialize.Serialize(list); } } }
namespace AssemblyTest { class Program { private static Program pro = new Program(); static void Main(string[] args) { pro.GetAssemblyInfo(); pro.LoadAssembly(); Console.ReadLine(); } /// <summary> /// 动态读取DLL,执行其中的方法 /// </summary> public void LoadAssembly() { //DLL所在的绝对路径 Assembly assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "Entity.dll"); //注意写法:程序集.类名 Type type = assembly.GetType("Entity.GetData"); //获取类中的公共方法GetResule MethodInfo methed = type.GetMethod("GetResule"); //创建对象的实例 object instance = System.Activator.CreateInstance(type); //执行方法 new object[]为方法中的参数 object result = methed.Invoke(instance, new object[] { }); } /// <summary> /// //获取程序集信息 /// </summary> public void GetAssemblyInfo() { Type type = typeof(Program); Assembly assembly = Assembly.GetExecutingAssembly(); Console.WriteLine("命名空间:{0}", type.Namespace); Console.WriteLine("程序集:{0}", type.Assembly); Console.WriteLine("类的名字{0}", type.Name); Console.WriteLine("类的全部名字{0}", type.FullName); Console.WriteLine("基类:{0}", type.BaseType); Console.WriteLine("----------------------------"); Console.WriteLine("程序集的名称:{0}", assembly.GetName()); Console.WriteLine("程序集的全名:{0}", assembly.FullName); Console.WriteLine("程序集的版本:{0}", assembly.GetName().Version); Console.WriteLine("程序集的位置:{0}", assembly.Location); Console.WriteLine("程序集所在目录:{0}", AppDomain.CurrentDomain.BaseDirectory); } } }
标签:
原文地址:http://www.cnblogs.com/wwj1992/p/5906727.html