如何优化此代码
var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(t => type.IsAssignableFrom(t));
这段代码比我想要的要慢。有人可以建议一种更优化的方法来用 C# 进行编码吗?
var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(t => type.IsAssignableFrom(t));
This code is going slower than I would like. Can someone suggest a more optimal way to code this in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在迭代已加载/引用的所有程序集中的所有类型。但您想要的类型就是您的类型,因此您知道它不在任何系统程序集中。例如,如果您的程序未安装在全局程序集缓存中,您可以过滤掉全局程序集缓存中的程序集:
如果您的应用程序安装在 GAC 中,您可以使用其他过滤策略将程序集限制为您自己的程序集。
You are iterating over all types in all assemblies you have loaded/referenced. But the type you want is your type so you know it isn't in any of the system assemblies. So for example you can filter out assemblies in the global assembly cache if you program isn't installed there:
You can use other filtering strategies to restrict the assemblies to your own if your application is installed in the GAC.
ToList()
完全是多余的,尽管这不太可能导致任何速度减慢:仅供参考,上面的代码应该相对快,它仅在您尝试通过
types
枚举 .Net 框架承担的繁重工作。除此之外,如果不了解更多关于您要做什么的信息,就没有什么可以优化的 - 上面的内容获取了加载到当前域中的所有程序集中所有类型
t
的枚举,其中typeof( TInterface).IsAssignableFrom(t)
- 如果加载了很多类型/程序集,那么恐怕这将需要一些时间。您能告诉我们更多关于您正在尝试做的事情吗?
The
ToList()
is entirely redundant, although this is very unlikely to cause any slowdown:FYI the above code should be relatively quick, its only at the point where you attempt to enumerate through
types
that the .Net framework does the heavy lifting.Other than that there is nothing to be optimised without knowing more about what you are trying to do - the above gets an enumeration of all types
t
in all assemblies loaded into the current domain wheretypeof(TInterface).IsAssignableFrom(t)
- if there are a lot of types / assemblies loaded then I'm afraid that this is going to take some time.Can you tell us more about what you are trying to do?