Finding All Derived Types of a Type
In programming, it is often necessary to identify all types that inherit from a specific base type. Currently, a common approach is to iterate through all types in the loaded assemblies and check if they are assignable to the base type.
However, a more efficient and cleaner method is to utilize a LINQ query to retrieve all derived types:
var listOfDerivedTypes = ( from domainAssembly in AppDomain.CurrentDomain.GetAssemblies() from type in domainAssembly.GetTypes() where typeof(BaseType).IsAssignableFrom(type) select type).ToArray();
This query searches for all types within the assemblies loaded into the current AppDomain and filters for types that can be assigned to the base type, effectively returning a list of derived types.
Fluent Version and Details:
The code can be expressed in a more fluent style:
var listOfDerivedTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(domainAssembly => domainAssembly.GetTypes()) .Where(type => typeof(BaseType).IsAssignableFrom(type)) .ToArray();
Additional Considerations:
The above is the detailed content of How Can I Efficiently Find All Derived Types of a Base Type in C#?. For more information, please follow other related articles on the PHP Chinese website!