在给定的命名空间下,我有一组实现接口的类.我们称之为ISomething
.我有另一个类(让我们称它CClass
),它知道ISomething
但不知道实现该接口的类.
我希望CClass
找到所有的实现ISomething
,实例化它的实例并执行该方法.
有没有人知道如何用C#3.5做到这一点?
Mat*_*ton 130
一个有效的代码示例:
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
}
Run Code Online (Sandbox Code Playgroud)
编辑添加了对无参数构造函数的检查,以便对CreateInstance的调用成功.
Mit*_*nny 10
您可以使用以下命令获取已加载程序集的列表:
Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
Run Code Online (Sandbox Code Playgroud)
从那里,您可以获得程序集中的类型列表(假设公共类型):
Type[] types = assembly.GetExportedTypes();
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过在对象上查找该接口来询问每种类型是否支持该接口:
Type interfaceType = type.GetInterface("ISomething");
Run Code Online (Sandbox Code Playgroud)
不确定是否有更有效的方法来做反射.
使用Linq的一个例子:
var types =
myAssembly.GetTypes()
.Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
Run Code Online (Sandbox Code Playgroud)