Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

.net - List of classes in an assembly C#

I want to get the list of classes in an assembly, as an output i want a List[Interface] not a List[string], as "Interface" is the interface from which inherits the classes of my assembly. I don't know if my question makes sense but if any one has the answer i would very much thankful. I already tried this solution: List of classes in an assembly, but it gives a list[string] containing the classes namesso it didn't help because i need the list of the classes that inherits from my interface. Thank you and have a nice day all :)

As an edit for my question, I used activator.createinstance(type t) to create instances of my classes so here is the code :

   Assembly assembly = typeof(Interface1<double, double>).Assembly;

   List<Interface> Classes = new List<Interface>();

   foreach (Type type in assembly.GetExportedTypes())

   {
      var Attributes = type.GetCustomAttributes<FilterAttribute>();
      //select the classes with attribute [Filter]

      if (Attributes.Any())

      {
                TypeOfFilters.Add(type);

      }

      foreach (var i in TypeOfFilters)

      {
            var inst = Activator.CreateInstance(i);

            Classes.Add((Interface) inst);


      }

   }

i get the error "System.IO.FileNotFoundException : Could not load file or assembly"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a little class I whipped up some weeks back when I was bored, this does what you're asking of - if I understand the question correctly.

Your applications must implement IPlugin, and must be dropped in a "Plugins" folder in the executing directory.

public interface IPlugin
{
    void Initialize();
}
public class PluginLoader
{
    public List<IPlugin> LoadPlugins()
    {
        List<IPlugin> plugins = new List<IPlugin>();

        IEnumerable<string> files = Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "Plugins"),
            "*.dll",
            SearchOption.TopDirectoryOnly);

        foreach (var dllFile in files)
        {
            Assembly loaded = Assembly.LoadFile(dllFile);

            IEnumerable<Type> reflectedType =
                loaded.GetExportedTypes().Where(p => p.IsClass && p.GetInterface(nameof(IPlugin)) != null);

            plugins.AddRange(reflectedType.Select(p => (IPlugin) Activator.CreateInstance(p)));
        }

        return plugins;
    }
}

Following from Paul's recommendation in the comments, here's a variation using MEF, referencing the System.ComponentModel.Composition namespace.

namespace ConsoleApplication18
{
    using System;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.IO;
    using System.Linq;

    public interface IPlugin
    {
        void Initialize();
    }
    class Program
    {
        private static CompositionContainer _container;
        static void Main(string[] args)
        {
            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(Directory.GetCurrentDirectory(), "Plugins")));

            _container = new CompositionContainer(catalog);

            IPlugin plugin = null;
            try
            {
                _container.ComposeParts();

                // GetExports<T> returns an IEnumerable<Lazy<T>>, and so Value must be called when you want an instance of the object type.
                plugin = _container.GetExports<IPlugin>().ToArray()[0].Value;
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }

            plugin.Initialize();
            Console.ReadKey();
        }
    }
}

and the DLL file - also referencing the System.ComponentModel.Composition namespace to set the ExportAttribute

namespace FirstPlugin
{
    using System.ComponentModel.Composition;

    [Export(typeof(IPlugin))]
    public class NamePlugin : IPlugin
    {
        public void Initialize() { }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...