我可以将 Activator.CreateInstance 与接口一起使用吗?

编程入门 行业动态 更新时间:2024-10-26 22:19:58
本文介绍了我可以将 Activator.CreateInstance 与接口一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个例子:

Assembly asm = Assembly.Load("ClassLibrary1"); Type ob = asm.GetType("ClassLibrary1.UserControl1"); UserControl uc = (UserControl)Activator.CreateInstance(ob); grd.Children.Add(uc);

我正在创建一个类的实例,但是如何创建一个实现某些接口的类的实例?即 UserControl1 实现 ILoad 接口.

There I'm creating an instance of a class, but how can I create an instance of a class which implements some interface? i.e. UserControl1 implements ILoad interface.

U:我可以稍后将对象转换为接口,但我不知道程序集中的哪种类型实现了接口.

U: I can cast object to interface later, but I don't know which type in the assemblies implements the interface.

推荐答案

这是我用过几次的一些代码.它在程序集中查找实现特定接口的所有类型:

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 中的所有类型都实现了 ILoad.

Then you have all types in ClassLibrary1 that implement ILoad.

然后你可以实例化它们:

You could then instantiate all of them:

ILoad[] instantiatedTypes = iLoadTypes.Select(t => (ILoad)Activator.CreateInstance(t)).ToArray();

更多推荐

我可以将 Activator.CreateInstance 与接口一起使用吗?

本文发布于:2023-10-16 11:41:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   Activator   CreateInstance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!