gpt4 book ai didi

c# - 从多个程序集中检索实现接口(interface)的对象

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:51 25 4
gpt4 key购买 nike

我想检索实例化类的枚举,这些实例化类实现了解决方案文件夹中多个程序集中的接口(interface)。

我有以下文件夹结构(如果这有意义的话):

Solution
-SolutionFolder
- Project1
- class implementing interface I would like to find
- other classes

- Project2
- class implementing interface I would like to find
- other classes

-MainProject
- classes where my code is running in which I would like to retrieve the list of classes

因此,如果正在实现的接口(interface)是ISettings , 那么我想要一个 IEnumerable<ISettings>引用该接口(interface)的实例化对象。

到目前为止,我已经使用反射从已知类名中检索实现接口(interface)的类:

IEnumerable<ISettings> configuration = 
(from t in Assembly.GetAssembly(typeof(CLASSNAME-THAT-IMPLEMENTs-INTERFACE-HERE)).GetTypes()
where t.GetInterfaces().Contains(typeof(ISettings)) && t.GetConstructor(Type.EmptyTypes) != null
select (ISettings)Activator.CreateInstance(t)).ToList();

但这是一个单独的程序集,我实际上不知道类名。

这可以使用反射来实现还是需要更多东西?

最佳答案

只要您只谈论加载到 AppDomain 中的程序集(它们必须是为了执行您之后的操作),您就可以使用类似这样的方法来遍历它们:

AppDomain.CurrentDomain
.GetAssemblies().ToList()
.ForEach(a => /* Insert code to work with assembly here */);

或者,如果您将它们加载到不同的 AppDomain 中,您可以使用一个实例来代替上面的 AppDomain.CurrentDomain

关于c# - 从多个程序集中检索实现接口(interface)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com