Home > Backend Development > C++ > How Can I Efficiently Find All Derived Types of a Given Type in .NET?

How Can I Efficiently Find All Derived Types of a Given Type in .NET?

Susan Sarandon
Release: 2025-01-01 03:58:11
Original
921 people have browsed it

How Can I Efficiently Find All Derived Types of a Given Type in .NET?

Identifying Derived Types Efficiently

In .NET, finding all derived types of a given type is a useful task often encountered during runtime operations. A common approach involves iterating through all types in loaded assemblies and checking for assignability to the target type. However, this method can be both slow and code-cluttered.

A more performant and elegant solution is to leverage the power of LINQ:

var listOfDerived = (
    from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in domainAssembly.GetTypes()
    where typeof(BaseType).IsAssignableFrom(type)
    select type).ToArray();
Copy after login

This Linq query efficiently searches through all assemblies and their types, selecting only those that inherit from the specified base type.

Optimization and Additional Considerations

To further optimize performance, consider using domainAssembly.GetExportedTypes() instead of GetTypes(). This retrieves only publicly visible types, potentially reducing the number of checks required.

Additionally, note that IsAssignableFrom includes the base type itself. If necessary, exclude it by adding && type != typeof(BaseType). To filter for concrete classes only, include && !type.IsAbstract.

Conclusion

By utilizing LINQ and considering these optimizations, finding derived types becomes a highly efficient and straightforward task, significantly improving the performance and readability of your code.

The above is the detailed content of How Can I Efficiently Find All Derived Types of a Given Type in .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template