首页 > 解决方案 > 有没有办法检查文件夹中的类,然后自动实例化它们?

问题描述

简短地说,我的程序是比较算法。目前,每当我添加或删除某些算法时,我都必须更改代码。我正在使用 C#。

我的想法是只检查目录中的类,然后为该目录中的每个对象在列表中实例化它(或字典,但我还不太了解这些,但现在让我们说列表)。这样我就不必手动添加每个算法,并且可以通过在所述文件夹中添加或删除类来添加或删除类。

因此,每当我编译我的程序时,它都会通过 src/model/algorithms,获取每个 ac# 类的文件,然后将该类的一个实例添加到列表中。

这可能吗,我该怎么做?

标签: c#oopinstantiation

解决方案


据我了解,您正在编写一个必须运行一些“算法”的可执行文件。您的算法被实现为存在于可执行文件程序集中的类。您不想硬编码可执行文件必须执行的算法,但您希望它们能够自动被发现。

然后简单定义一个接口:

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

所以你看,这与类文件无关。


推荐阅读