295
296
核心代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProOperation;
//通过反射动态加载
using System.Reflection;
using System.IO;
namespace ProFactory
{
//通过这个工厂去获得所有子类的
public class Factory
{
//这个工厂的目的是返回父类,创建子类生成后返回该父类
public static Operation GetOper(string type, int n1, int n2)
{
Operation oper = null;
//动态加载程序集
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plug");
//【关键点】:这里需要根据我们拿到的程序集文件,去动态地创建子类,然后给父类,并且返回
//获得Plug路径下面的所有程序集文件的全路径
string files = Directory.GetFiles(path, "*.dll"); //"E:\\2018C#Learn\\Projects\\ConsoleApp2\\Caculator\\bin\\Debug\\Plug\\ProAdd.dll"
//遍历文件
foreach (string item in files)
{
//加载文件
Assembly ass = Assembly.LoadFile(item);
//获得程序集中所有公开的数据类型
//Type types = ass.GetExportedTypes();
Type types = ass.GetTypes();
foreach (Type tt in types)
{
//判断当前的数据类型是否为我需要的类型(是子类,而且不是抽象的)
if (tt.IsSubclassOf(typeof(Operation)) && !tt.IsAbstract)
{
//创建子类对象赋值给Oper( 抽象类是不能实例化的)
Object o = Activator.CreateInstance(tt, n1, n2);
oper = (Operation)o;
}
if (type == oper.Type)
{
break;
}
else
{
oper = null;
}
}
}
return oper;
}
}
}
评论
填写昵称与邮箱即可评论,无需登录。