c# - 有没有办法检查文件夹中的类,然后自动实例化它们?
问题描述
简短地说,我的程序是比较算法。目前,每当我添加或删除某些算法时,我都必须更改代码。我正在使用 C#。
我的想法是只检查目录中的类,然后为该目录中的每个对象在列表中实例化它(或字典,但我还不太了解这些,但现在让我们说列表)。这样我就不必手动添加每个算法,并且可以通过在所述文件夹中添加或删除类来添加或删除类。
因此,每当我编译我的程序时,它都会通过 src/model/algorithms,获取每个 ac# 类的文件,然后将该类的一个实例添加到列表中。
这可能吗,我该怎么做?
解决方案
据我了解,您正在编写一个必须运行一些“算法”的可执行文件。您的算法被实现为存在于可执行文件程序集中的类。您不想硬编码可执行文件必须执行的算法,但您希望它们能够自动被发现。
然后简单定义一个接口:
public interface IAlgorithm
{
string Name { get; }
void Execute();
}
让你的算法实现这个接口:
public class FooAlgorithm : IAlgorithm
{
public string Name => "Foo";
public void Execute()
{
Console.WriteLine("Fooing the foo");
}
}
public class BarAlgorithm : IAlgorithm
{
public string Name => "Bar";
public void Execute()
{
Console.WriteLine("Barring the bar");
}
}
现在在程序启动时,扫描您的程序集以查找实现此接口的类型:
var algorithmTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(IAlgorithm).IsAssignableFrom(p))
.ToList();
foreach (var algorithmType in algorithmTypes )
{
var algorithm = (IAlgorithm)Activator.CreateInstance(algorithmType);
Console.WriteLine($"Executing algorithm '{algorithm.Name}'...");
algorithm.Execute();
}
所以你看,这与类文件无关。
推荐阅读
- css - 在不同的 bootstrap4 标签栏之间移出和移入内容
- c# - Regex.Replace 或 String.Replace 不适用于 Linux 环境中的主机 URL
- ios - 控制台中lldb中的Xcode12 po命令在范围内找不到变量
- java - 这个关键字在 lambda 表达式中指向哪个对象?
- python - 如何在python中找到具有重复元素的元组?
- sql - 从 SQL Server / ORACLE 路径中提取文件夹名称和级别
- ruby-on-rails - rails around_action 如何与 return 语句一起使用
- sorting - 排序算法选择
- sql - sql server中的CTE返回空值但不是NULL问题
- winapi - 其余的 TMessage 缺少参数在哪里?