Created
November 3, 2023 16:13
-
-
Save bronumski/f3639f0c861642e58507e1c10df78f2d to your computer and use it in GitHub Desktop.
Type extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class TypeExtensions | |
{ | |
public static IEnumerable<Type> GetInstanceTypesImplementing<T>( | |
this Assembly assembly, params Assembly[] assemblies) | |
{ | |
var serviceType = typeof(T); | |
return assemblies.Union(new [] { assembly }).SelectMany(x => x.GetTypes()) | |
.Where( x => x.IsClass && !x.IsAbstract && serviceType.IsAssignableFrom( x ) ); | |
} | |
public static IEnumerable<Type> GetTypesDecoratedWith<T>( | |
this Assembly assembly, params Assembly[] assemblies ) where T : Attribute | |
{ | |
var decoratorType = typeof(T); | |
return assemblies.Union(new [] { assembly }).SelectMany(x => x.GetTypes()) | |
.Where( x => x.IsClass && !x.IsAbstract && x.GetCustomAttributes(decoratorType, true ).Any()); | |
} | |
public static bool ImplementsGenericInterface( | |
this Type typeToInspect, Type genericInterface) | |
=> genericInterface.IsGenericTypeDefinition is false | |
? throw new InvalidOperationException( $"Expected type '{genericInterface}' to be a generic type definition" ) | |
: typeToInspect | |
.GetInterfaces() | |
.Any( x => x.IsGenericType && x.GetGenericTypeDefinition() == genericInterface ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment