在给定的命名空间下,我有一组实现接口的类。我们称之为ISomething
。我有另一个类(让我们称之为CClass
)知道ISomething
,但不知道实现该接口的类。
我希望CClass
查找ISomething
的所有实现,实例化它的实例并执行该方法。
是否有人知道如何使用C#3.5做到这一点?
答案 0 :(得分:129)
工作代码示例:
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ISomething))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ISomething;
foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}
编辑添加了对无参数构造函数的检查,以便对CreateInstance的调用成功。
答案 1 :(得分:10)
您可以使用以下命令获取已加载程序集的列表:
Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
从那里,您可以获得程序集中的类型列表(假设公共类型):
Type[] types = assembly.GetExportedTypes();
然后,您可以通过在对象上找到该接口来询问每种类型是否支持该接口:
Type interfaceType = type.GetInterface("ISomething");
不确定是否有更有效的方法可以通过反射进行此操作。
答案 2 :(得分:8)
使用Linq的例子:
var types =
myAssembly.GetTypes()
.Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
答案 3 :(得分:3)
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (t.GetInterface("ITheInterface") != null)
{
ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
executor.PerformSomething();
}
}
答案 4 :(得分:2)
您可以使用以下内容并根据您的需要进行定制。
var _interfaceType = typeof(ISomething);
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var types = GetType().GetNestedTypes();
foreach (var type in types)
{
if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
{
ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
something.TheMethod();
}
}
此代码可以使用一些性能增强功能,但这是一个开始。
答案 5 :(得分:0)
也许我们应该这样做
foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() )
instance.Execute();