Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c# - Get all derived types of a type

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

  1. get all types in used Assemblies
  2. check my type with all those types if it is 'IsAssignable'

I was wondering if theres a better way todo this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I once used this Linq-method to get all types inheriting from a base type B:

    var listOfBs = (
                    from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                    // alternative: from domainAssembly in domainAssembly.GetExportedTypes()
                    from assemblyType in domainAssembly.GetTypes()
                    where typeof(B).IsAssignableFrom(assemblyType)
                    // alternative: where assemblyType.IsSubclassOf(typeof(B))
                    // alternative: && ! assemblyType.IsAbstract
                    select assemblyType).ToArray();

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

  • 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 domainAssembly.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).
  • One may want/need to check for a 'real' class: && ! assemblyType.IsAbstract. (Note that all interfaces are considered abstract, see MSDN.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...