简体   繁体   English

如何优化此代码

[英]How to optimize this Code

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#? 有人可以建议一种更优化的方式来用C#编写代码吗?

The ToList() is entirely redundant, although this is very unlikely to cause any slowdown: ToList()完全是冗余的,虽然这不太可能导致任何减速:

var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(t => type.IsAssignableFrom(t));

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. 仅供参考,上面的代码应该相对较快,它只是在您试图通过types枚举.Net框架完成繁重工作时。

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 where typeof(TInterface).IsAssignableFrom(t) - if there are a lot of types / assemblies loaded then I'm afraid that this is going to take some time. 除此之外,没有什么不知道更多关于你正在尝试做的最优化-上面得到的所有类型的枚举t在加载到当前域中的所有组件,其中typeof(TInterface).IsAssignableFrom(t) -如果有加载了很多类型/程序集然后我担心这需要一些时间。

Can you tell us more about what you are trying to do? 你能告诉我们更多关于你想要做什么的事吗?

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: 例如,如果您没有安装程序,则可以过滤掉全局程序集缓存中的程序集:

var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.GlobalAssemblyCache)
    .SelectMany(s => s.GetTypes())
    .Where(t => type.IsAssignableFrom(t));

You can use other filtering strategies to restrict the assemblies to your own if your application is installed in the GAC. 如果您的应用程序安装在GAC中,则可以使用其他过滤策略将程序集限制为您自己的程序集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM