程序集C#中的类列表 [英] List of classes in an assembly C#

查看:244
本文介绍了程序集C#中的类列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取程序集中的类的列表,作为输出,我想要一个List [Interface]而不是List [string],因为 Interface是从其继承我程序集类的接口。我不知道我的问题是否有意义,但是如果有人有答案,我将非常感谢。
我已经尝试过此解决方案:程序集中的类列表 ,但是它提供了一个包含类名称的列表[string],所以它没有帮助,因为我需要从我的接口继承的类的列表。
谢谢,并祝大家愉快:

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 :)

作为对我的问题的编辑,我使用了activator.createinstance(type t)创建我的实例。类,因此代码如下:

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


      }

   }

我收到错误消息 System.IO.FileNotFoundException:无法加载文件或程序集

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

推荐答案

这是我鞭打的一个小类几周前,当我无聊的时候,这符合您的要求-如果我正确理解了这个问题。

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.

您的应用程序必须实现IPlugin,并且必须将其放在执行目录中的 Plugins文件夹中。

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

根据Paul在评论中的建议,这里有一个变化使用MEF,引用 System.ComponentModel.Composition 命名空间。

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

和DLL文件-也引用 System.ComponentModel.Composition 命名空间来设置 ExportAttribute

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

这篇关于程序集C#中的类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆