118 lines
4.1 KiB
C#
118 lines
4.1 KiB
C#
using PluginBase;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using 加载dll;
|
|
|
|
namespace 加载Dll
|
|
{
|
|
class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
try
|
|
{
|
|
if (args.Length == 1 && args[0] == "/d")
|
|
{
|
|
Console.WriteLine("按下任何按钮开始运行...");
|
|
Console.ReadLine();
|
|
}
|
|
|
|
// 从插件加载指令
|
|
string[] pluginPaths = new string[]
|
|
{
|
|
"D:\\插件\\你好插件.dll",
|
|
"C:\\Users\\misaka20001\\source\\repos\\加载dll\\你好插件\\bin\\Debug\\net6.0\\你好插件.dll"
|
|
// Paths to plugins to load.
|
|
// 这里填写需要加载插件的路径
|
|
};
|
|
|
|
IEnumerable<ICommand> commands = pluginPaths.SelectMany(pluginPath =>
|
|
{
|
|
Assembly pluginAssembly = 加载插件(pluginPath);
|
|
return 创建命令(pluginAssembly);
|
|
}).ToList();
|
|
|
|
if (args.Length == 0)
|
|
{
|
|
Console.WriteLine("命令: ");
|
|
// 输出加载的命令.
|
|
foreach (ICommand command in commands)
|
|
{
|
|
Console.WriteLine($"{command.名称}\t - {command.描述}");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
foreach (string commandName in args)
|
|
{
|
|
Console.WriteLine($"-- {commandName} --");
|
|
|
|
// Execute the command with the name passed as an argument.
|
|
// 使用作为参数传递的名称执行命令
|
|
ICommand? command = commands.FirstOrDefault(c => c.名称 == commandName);
|
|
if (command == null)
|
|
{
|
|
Console.WriteLine("没有找到任何已知命令");
|
|
return;
|
|
}
|
|
|
|
command.执行();
|
|
|
|
Console.WriteLine();
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex);
|
|
}
|
|
}
|
|
|
|
static Assembly 加载插件(string 相对路径)
|
|
{
|
|
//throw new NotImplementedException();//未实现异常
|
|
string? root = Path.GetFullPath(Path.Combine(
|
|
Path.GetDirectoryName(
|
|
Path.GetDirectoryName(
|
|
Path.GetDirectoryName(
|
|
Path.GetDirectoryName(
|
|
Path.GetDirectoryName(path:typeof(Program).Assembly.Location)))))));
|
|
|
|
string pluginLocation = Path.GetFullPath(Path.Combine(root, 相对路径.Replace('\\', Path.DirectorySeparatorChar)));
|
|
Console.WriteLine($"加载插件: {pluginLocation}");
|
|
加载插件上下文 loadContext = new(pluginLocation);
|
|
return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
|
|
}
|
|
|
|
static IEnumerable<ICommand> 创建命令(Assembly 程序集)
|
|
{
|
|
int count = 0;
|
|
|
|
foreach (Type type in 程序集.GetTypes())
|
|
{
|
|
if (typeof(ICommand).IsAssignableFrom(type))
|
|
{
|
|
ICommand? result = Activator.CreateInstance(type) as ICommand;
|
|
if (result != null)
|
|
{
|
|
count++;
|
|
yield return result;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (count == 0)
|
|
{
|
|
string availableTypes = string.Join(",", 程序集.GetTypes().Select(t => t.FullName));
|
|
throw new ApplicationException(
|
|
$"在{程序集.Location}的{程序集}中找不到实现了ICommand的任何可用类型\n"+
|
|
$"可用类型: {availableTypes}");
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
} |