Finding Derived Types of a Specified Type
In programming, it is often necessary to determine all derived types of a given base type. Traditionally, this has been achieved through laborious techniques such as iterating over all types in loaded assemblies and manually checking for assignability to the target type.
However, a more efficient and elegant solution exists using LINQ (Language Integrated Query). The following code snippet provides a straightforward and performant way to accomplish this task:
var listOfDerivedTypes = ( from domainAssembly in AppDomain.CurrentDomain.GetAssemblies() from type in domainAssembly.GetTypes() where typeof(BaseTypeName).IsAssignableFrom(type) select type).ToArray();
Alternative Fluent Syntax:
The LINQ expression can also be written in a more fluent style for enhanced readability:
var listOfDerivedTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(domainAssembly => domainAssembly.GetTypes()) .Where(type => typeof(BaseTypeName).IsAssignableFrom(type)) .ToArray();
Customizations:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3