我可以使用Activator.CreateInstance与接口? [英] Can I use Activator.CreateInstance with an Interface?
本文介绍了我可以使用Activator.CreateInstance与接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个例子:
Assembly asm = Assembly.Load("ClassLibrary1");
Type ob = asm.GetType("ClassLibrary1.UserControl1");
UserControl uc = (UserControl)Activator.CreateInstance(ob);
grd.Children.Add(uc);
有我创建一个类的实例,但如何创建一个实现了某些接口的类的实例?即的UserControl1 工具 I负荷接口。
U:我可以投对象以后接口,但我不知道是哪个类型的组件实现接口
U: I can cast object to interface later, but I don't know which type in the assemblies implements the interface.
推荐答案
这是一些$ C $词都用过几次。它发现所有类型的实现某个接口的组件:
This is some code i have used a few times. It finds all types in an assembly that implement a certain interface:
Type[] iLoadTypes = (from t in Assembly.Load("ClassLibrary1").GetExportedTypes()
where !t.IsInterface && !t.IsAbstract
where typeof(ILoad).IsAssignableFrom(t)
select t).ToArray();
然后你拥有所有类型的ClassLibrary1的实现 I负荷
。
您可以再实例化所有的人:
You could then instantiate all of them:
ILoad[] instantiatedTypes =
iLoadTypes.Select(t => (ILoad)Activator.CreateInstance(t)).ToArray();
这篇关于我可以使用Activator.CreateInstance与接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文