C#多态 - 从DLL文件加载类 [英] C# polymorphism - load classes from DLL files
问题描述
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屋!