获取实现接口的所有类型 [英] Getting all types that implement an interface
本文介绍了获取实现接口的所有类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用反射,我怎样才能用最少的代码和最小化迭代获得所有用 C# 3.0/.NET 3.5 实现接口的类型?
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
这是我想重写的:
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
推荐答案
我的在 c# 3.0 中是这样的 :)
Mine would be this in c# 3.0 :)
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
基本上,最少的迭代次数总是:
Basically, the least amount of iterations will always be:
loop assemblies
loop types
see if implemented.
这篇关于获取实现接口的所有类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文