Finding Derived Types: Efficient and Comprehensive Approach
In software development, it can be crucial to identify all types derived from a given base type. While common approaches involve checking for is assignability, they may not be optimal in terms of performance or elegance.
Linq-Based Solution
A more efficient and syntactically concise approach is to leverage Linq. The following code snippet demonstrates a Linq query that finds all types inheriting from a base type B:
var listOfBs = ( from domainAssembly in AppDomain.CurrentDomain.GetAssemblies() // alternative: from domainAssembly in domainAssembly.GetExportedTypes() from type in domainAssembly.GetTypes() where typeof(B).IsAssignableFrom(type) // alternative: && type != typeof(B) // alternative: && ! type.IsAbstract // alternative: where type.IsSubclassOf(typeof(B)) select type).ToArray();
Fluent API for Enhanced Readability
To improve readability and maintainability, the above query can be refactored using a fluent API:
var listOfBs = AppDomain.CurrentDomain.GetAssemblies() // alternative: .GetExportedTypes() .SelectMany(domainAssembly => domainAssembly.GetTypes()) .Where(type => typeof(B).IsAssignableFrom(type) // alternative: => type.IsSubclassOf(typeof(B)) // alternative: && type != typeof(B) // alternative: && ! type.IsAbstract ).ToArray();
Considerations and Enhancements
This Linq-based approach offers several advantages:
Conclusion
This Linq-based solution provides a performant and extensible means to retrieve all derived types of a given base type. Its versatility and flexibility make it adaptable to diverse use cases.
The above is the detailed content of How Can I Efficiently Find All Derived Types in C#?. For more information, please follow other related articles on the PHP Chinese website!