[英]Creating object of each type which implements Interface
In my program, I use a number of sources to obtain data. 在我的程序中,我使用了许多来源来获取数据。 The actual implementation does not really matter, but they all implement a "Source" interface which has a call to fetch data given a particular input. 实际实现并不重要,但它们都实现了一个“源”接口,该接口在给定特定输入的情况下调用获取数据。
When I need data, I want to call all the sources one at a time and do something with the data. 当我需要数据时,我希望一次调用所有源代码并对数据执行某些操作。
Currently I do this: 目前我这样做:
List<Source> sources = new List<Source>()
sources.Add(new SourceA());
sources.Add(new SourceB());
//...
//----
foreach (Source source in sources)
{
string data = source.getData(input);
//do something with the data
}
The issue is that I need to hard-code the insertion of the sources into the list. 问题是我需要硬编码将源插入列表。 Is there a way (using reflection perhaps) of automating the process? 是否有一种方法(可能使用反射)自动化过程? I'd like the list to contain all objects which implement the 'Source' interface - without having to hard-code it myself. 我希望列表包含实现“Source”接口的所有对象 - 而不必自己进行硬编码。
You can use reflection to search the assemblies for classes that implement your interface and create instances. 您可以使用反射在程序集中搜索实现接口和创建实例的类。 I would consider renaming to ISource unless there is shared code in the base class. 我会考虑重命名为ISource,除非基类中有共享代码。
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
if (typeof(ISource).IsAssignableFrom(type))
{
sources.Add((ISource)Activator.CreateInstance(type));
}
}
Here is some code I use to load Addons stored in an external assembly. 这是我用来加载存储在外部程序集中的Addons的一些代码。 The bit towards the bottom shows how to get all types with a certain Interface called 'IWAPAddon' this is the part of code you can use: 底部的位显示如何使用称为“IWAPAddon”的特定接口获取所有类型,这是您可以使用的代码的一部分:
//If the plugin assembly is not aleady loaded, load it manually
if ( PluginAssembly == null )
{
PluginAssembly = Assembly.LoadFile( oFileInfo.FullName );
}
if ( PluginAssembly != null )
{
//Step through each module
foreach ( Module oModule in PluginAssembly.GetModules() )
{
//step through the types in each module
foreach ( Type oModuleType in oModule.GetTypes() )
{
foreach ( Type oInterfaceType in oModuleType.GetInterfaces() )
{
if ( oInterfaceType.Name == "IWAPAddon" )
{
this.Addons.Add( oModuleType );
}
}
}
}
}
Based on Slugart's suggestion: 根据Slugart的建议:
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.GetInterfaces().Contains(typeof(ISource)) && type.IsInterface == false
{
sources.Add((ISource)Activator.CreateInstance(type));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.