LoadDll/加载dll/Program.cs

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}");
}
}
}
}