码迷,mamicode.com
首页 > Web开发 > 详细

.NET 程序集Assembly使用

时间:2017-01-03 07:22:24      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:count   add   app   try   实例   get   添加   instance   title   

概述

  一直以来,我们都在用C#编写程序,编写程序的时候,我们用到继承、多态、接口以及泛型,我们也都明白子类可以继承抽象类,并能够重写父类的抽象方法,可是大家是否想过,如下几个问题:

  1、凡树必有根和叶,类的继承也如此,如何通过程序集查找所有继承父类的之类的程序集名称?

  2、如果程序B被其他程序调用,如何通过程序集查询调用B的所有程序?

  3、如何查询当前项目通过添加引用了哪些程序集?

带上上面的三个问题,我们来学习下.NET 程序集 Assembly。

查询继承父类的程序集合BaseType

  .NET的程序集对象Assembly有个属性BaseType,来返回当前程序集的基础类型,默认是Object。通过该属性可以判断某个程序集是否是继承了某个父类;

程序集B被A程序引用,获取A程序集的信息GetCallingAssembly

  .NET的程序集对象Assembly有个方法GetCallingAssembly获取当前程序集被调用的上级程序集的信息;

查找当前项目的程序集GetAssemblies

  查找当前项目所有程序集的方法System.AppDomain.CurrentDomain.GetAssemblies();

实例化对象

  通过程序集GetType()获取程序集的数据类型,通过Activator.CreateInstance(type) 便可创建响应的实例对象;

     整体使用的代码如下:BaseService是所有服务类的基类

            List<Type> TypeItemList = new List<Type>();
            //var ResultTypeList = Assembly.GetEntryAssembly();
            //if (ResultTypeList == null)
            //{
            //    ResultTypeList = Assembly.GetCallingAssembly();
            //    var ItemList = ResultTypeList.GetReferencedAssemblies().Where(p => p.GetType() == typeof(BaseService));                
            //}
            Assembly[] AssbyCustmList = System.AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assItem in AssbyCustmList)
            {
                TypeItemList.AddRange(assItem.GetTypes().Where(x => x.BaseType == typeof(BaseService)).ToList());
            }
            //IEnumerable<Type> TypeItemList = CurType.Assembly.GetExportedTypes().Where(x => x.BaseType == typeof(BaseService)).ToList();
            //IEnumerable<Type> TypeItemList = ResultTypeList.GetTypes().Where(x => x.BaseType == typeof(BaseService)).ToList();
            BaseService TarService = null;
            foreach (Type typeitem in TypeItemList)
            {
                if (_Reporttory.Count(p => p.GetType() == typeitem) == 0)
                {
                    TarService = (Activator.CreateInstance(typeitem) as BaseService);
                }
                else
                {
                    TarService = _Reporttory.First(p => p.GetType() == typeitem);
                }
                TarService.Start();
            }         

 

.NET 程序集Assembly使用

标签:count   add   app   try   实例   get   添加   instance   title   

原文地址:http://www.cnblogs.com/xibei666/p/6243424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!