①在主程序中
var floder = System.IO.Path.Combine(Environment.CurrentDirectory, "Animals"); //访问插件(dll所在文件夹)
var files = Directory.GetFiles(floder);//获取文件夹内的文件列表
var animalTypes = new List<Type>();//创建一个数组,用于存放插件
foreach (var file in files)
{
var assermbly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file); //加载程序集
var types = assermbly.GetTypes();
foreach (var type in types)
{
if (type.GetMethod("Voice") != null) //如果文件中的 Voice函数不为空
{
animalTypes.Add(type);
}
}
}
for (int i = 0; i < animalTypes.Count; i++)
{
textBox.AppendText($"{i + 1}.{animalTypes[i].Name}"); //列出 插件目录
}
int index = textBox.LineCount;
if (index > animalTypes.Count || index < 1)
{
MessageBox.Show("No such an animal Try again!");
}
int times = Convert.ToInt16(textBox1.Text);
var t = animalTypes[index - 1]; //获取最后一个插件
var m = t.GetMethod("Voice");
var o = Activator.CreateInstance(t); //动态创建一个 实例
m.Invoke(o, new object[] { times }); //调用
//插件内部必须要有 Voice的实现方式
② 准备一个外部类:右击解决方案→添加→新建项目→类库(Animals)→新建类Cat→完成代码→右键点击Animals生成→在Animals项目文件夹内,找到DLL,复制到主程序文件的Animals文件夹
namespace Animals
{
public void Cat
{
public string Voice(int times)
{
for (int i = 0; i < times; i++)
{
}
}
}
}
③第二步 中的缺点是,如果插件开发的存在一些错误,例如 Voice的 V写成小写,就会出错,改进方法 使用SDK,右击解决方案→添加→新建项目→类库(Baby.sdk)→新建接口IAnimal,新建UnfinishedAttribute类 继承Attribute,点击生成,将生成的 DLL复制出来→在主程序引用该DLL(可以直接引用)→在插件开发程序 引用DLL(通过搜索)
namespace baby.sdk
{
public interface IAnimal
{
void Voice(int times);
}
}
/
namespace baby.sdk
{
public class UnfinishedAttribute:Attribute
{
}
}
///
插件开发项目引入SDK后,直接在项目的类中继承 using 并SDK类 ,在函数头部加上[Unfinished]代表未开发完成,则不会加载读取
[Unfinished]
namespace Animals
{
public void Cat:IAnimal
{
public string Voice(int times)
{
for (int i = 0; i < times; i++)
{
}
}
}
}
修改主程序
var floder = System.IO.Path.Combine(Environment.CurrentDirectory, "Animals");
var files = Directory.GetFiles(floder);
var animalTypes = new List<Type>();
foreach (var file in files)
{
var assermbly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file); //加载程序集
var types = assermbly.GetTypes();
/*引入SDK之后*/
foreach (var type in types)
{
if (type.GetInterfaces().Contains(typeof(IAnimal))){
var isUn = type.GetCustomAttributes(false).Any(a => a.GetType() == typeof(UnfinishedAttribute));
if (isUn)
{
continue;
}
animalTypes.Add(type);
}
}
/*
foreach (var type in types)
{
// MessageBox.Show(type.GetMethod("Voice").ToString());
if (type.GetMethod("Voice") != null)
{
animalTypes.Add(type);
}
} //引入SDK之前 */
}
for (int i = 0; i < animalTypes.Count; i++)
{
textBox.AppendText($"{i + 1}.{animalTypes[i].Name}");
}
int index = textBox.LineCount;
if (index > animalTypes.Count || index < 1)
{
MessageBox.Show("No such an animal Try again!");
}
int times = Convert.ToInt16(textBox1.Text);
var t = animalTypes[index - 1];
var m = t.GetMethod("Voice");
var o = Activator.CreateInstance(t);
var a = o as IAnimal;
a.Voice(times);
/*
m.Invoke(o, new object[] { times }); //使用SDK前*/