C#多态 - 从DLL文件加载类 [英] C# polymorphism - load classes from DLL files

查看:185
本文介绍了C#多态 - 从DLL文件加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解决了这个问题的答案我在这个问题上遇到的问题,但是我想知道是否有可能扩展它。例如,如果我要让第三方为这个系统提供命令,那么会有一种方法可以将第一个答案扩展到我之前的一个问题,让它从文件夹中的所有DLL中加载所有的命令,然后列出它们在列表框中。

The responses I've got to this question have solved the problem I had in that question, but I'm wondering whether it's possible to extend it a bit. For example, if I were to have third parties contributing commands to this system, would there be a way of extending the first answer to my previous question to allow it to load all the commands from all the DLLs in a folder, and then list them in the list box.

可以吗?可以使用ICommand列表(作为我之前提出的问题的答案)。

Is that possible? Would it be able to work with a List of ICommand (as the answer to my previous question suggested).

推荐答案

是的。 / p>

Yes.

 Assembly commandAssembly = Assembly.Load("some/path")
 var commands = new List<ICommand>();

 foreach (Type type in commandAssembly.GetTypes())
 {
    if (type.GetInterface(typeof(ICommand).FullName) != null)
    {
       commands.Add((ICommand)Activator.CreateInstance(type));
    }
 }

但是,您可能会遇到关于装配的一些限制加载。你不能从任何地方加载程序集,否则你可以重新实现类似COM DLL的地狱。

However, you will probably run into some restrictions regarding assembly loading. You cannot just load assemblies from anywhere, otherwise you could reimplement something like COM DLL hell.

这篇关于C#多态 - 从DLL文件加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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