获取所有派生类型的类型 [英] Get all derived types of a type

查看:161
本文介绍了获取所有派生类型的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的(更好的性能和更好的code;)的方式来找到一个类型的所有派生类型? 目前,即时通讯使用的是这样的:

Is there a better (more performant or nicer code ;) way to find all derived Types of a Type? Currently im using something like:

  1. 在获得所有类型中使用的组件
  2. 检查我的类型与所有这些类型的,如果它是'IsAssignable

我在想,如果这个待办事项孤单更好的办法?

I was wondering if theres a better way todo this?

推荐答案

once用这种的LINQ方法:

I once used this Linq-method:

    var listOfBs = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                    from assemblyType in domainAssembly.GetTypes()
                    where typeof(B).IsAssignableFrom(assemblyType)
                    select assemblyType).ToArray();

修改:这似乎仍然是获得更多的代表(因此更多的意见),让我补充一些更多的细节:

EDIT: As this still seems to get more rep (thus more views), let me add some more details:

  • 如上面提到的链路状态,此方法使用反射在每次调用。所以反复使用该方法为相同类型时, 1大概可以使它更通过一次加载效率。
  • 安东的建议,也许你可以(微)采用优化它 Assembly.GetExportedTypes() 检索仅公开可见的类型(如果这是你所需要的)。
  • 诺多提到, Type.IsAssignable 也将得到原始(非衍生的)的类型。 ( Type.IsSubclassOf 不会,但 Type.IsSubclassOf 将无法正常工作,如果基本类型是一个接口)。
  • As the above-mentioned link states, this method uses Reflection on each call. So when using the method repeatedly for the same type, one could probably make it much more efficient by loading it once.
  • As Anton suggests, maybe you could (micro)optimize it using Assembly.GetExportedTypes() to retrieve only publicly visible types (if that's all you need).
  • As Noldorin mentions, Type.IsAssignable will also get the original (non-derived) type. (Type.IsSubclassOf will not, but Type.IsSubclassOf will not work if the base type is an interface).

这篇关于获取所有派生类型的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆