例項化實現介面的類(例如外掛啟用)

如果你希望應用程式支援外掛系統,例如從位於 plugins 資料夾中的程式集載入外掛:

interface IPlugin
{
    string PluginDescription { get; }
    void DoWork();
}

這個類將位於一個單獨的 dll 中

class HelloPlugin : IPlugin
{
    public string PluginDescription => "A plugin that says Hello";
    public void DoWork()
    {
        Console.WriteLine("Hello");
    }
}

你的應用程式的外掛載入器將找到 dll 檔案,獲取實現 IPlugin 的那些程式集中的所有型別,並建立這些檔案的例項。

    public IEnumerable<IPlugin> InstantiatePlugins(string directory)
    {
        var pluginAssemblyNames = Directory.GetFiles(directory, "*.addin.dll").Select(name => new FileInfo(name).FullName).ToArray();
        //load the assemblies into the current AppDomain, so we can instantiate the types later
        foreach (var fileName in pluginAssemblyNames)
            AppDomain.CurrentDomain.Load(File.ReadAllBytes(fileName));
        var assemblies = pluginAssemblyNames.Select(System.Reflection.Assembly.LoadFile);
        var typesInAssembly = assemblies.SelectMany(asm => asm.GetTypes());
        var pluginTypes = typesInAssembly.Where(type => typeof (IPlugin).IsAssignableFrom(type));
        return pluginTypes.Select(Activator.CreateInstance).Cast<IPlugin>(); 
    }