.NET开发设计模式-获取某个接口下面所有的派生类

时间:2021-11-09 20:14:17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConmonService
{
    class Program
    {
        /*获取某一个接口下面所有的子类*/
        static void Main(string[] args)
        {
            /*找单个程序集里面某个接口下面所有的派生类*/
            {

                /*找到某个程序集ICreateDTOService里面所有的类*/
                Assembly assembly = Assembly.Load("ICreateDTOService");

                /*找到程序集里面所有的类*/
                Type[] types = assembly.GetTypes();

                /*子类容器*/
                List<Type> TypeList = new List<Type>();

                foreach (var item in types)
                {
                    /*找到目标接口下面所有的派生类*/
                    if (item.GetInterface("ICreateDto") != null)
                    {
                        TypeList.Add(item);
                    }
                }
                /*获取完毕*/

            }
            /*找多个程序集[ICreateDTOService,ICreateDTOService.Demo1]里面的某个接口下面所有的派生类*/
            {
                List<Assembly> Assemblys = new List<Assembly>() {
                    Assembly.Load("ICreateDTOService"),
                    Assembly.Load("ICreateDTOService.Demo1")
                };
                List<Type> TypeList = new List<Type>();
                foreach (var AssemblyItem in Assemblys)
                {
                    TypeList.AddRange(AssemblyItem.GetTypes().Where(o => o.GetInterface("ICreateDto") != null).ToList<Type>());
                }
            }
            /*获取当前运行时引用的程序集中继承某个接口下面的派生类*/
            {
                List<Assembly> Assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList<Assembly>();
                List<Type> TypeList = new List<Type>();
                foreach (var AssemblyItem in Assemblys)
                {
                    TypeList.AddRange(AssemblyItem.GetTypes().Where(o => o.GetInterface("ICreateDto") != null).ToList<Type>());
                }
            }
        }
    }
}