diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-08-14 04:09:13 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-08-14 04:09:13 +0200 |
commit | 0d0511e35d9965fc0ea5190ae3347c3d77c3334c (patch) | |
tree | b4e0c336cbccc37bd14952b447868a577ea15540 /LibMatrix/Extensions/ClassCollector.cs | |
download | LibMatrix-0d0511e35d9965fc0ea5190ae3347c3d77c3334c.tar.xz |
Split LibMatrix into separate repo
Diffstat (limited to 'LibMatrix/Extensions/ClassCollector.cs')
-rw-r--r-- | LibMatrix/Extensions/ClassCollector.cs | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/LibMatrix/Extensions/ClassCollector.cs b/LibMatrix/Extensions/ClassCollector.cs new file mode 100644 index 0000000..f53850a --- /dev/null +++ b/LibMatrix/Extensions/ClassCollector.cs @@ -0,0 +1,22 @@ +using System.Reflection; + +namespace LibMatrix.Extensions; + +public class ClassCollector<T> where T : class { + static ClassCollector() { + if (!typeof(T).IsInterface) + throw new ArgumentException( + $"ClassCollector<T> must be used with an interface type. Passed type: {typeof(T).Name}"); + } + + public List<Type> ResolveFromAllAccessibleAssemblies() => AppDomain.CurrentDomain.GetAssemblies().SelectMany(ResolveFromAssembly).ToList(); + + public List<Type> ResolveFromObjectReference(object obj) => ResolveFromTypeReference(obj.GetType()); + + public List<Type> ResolveFromTypeReference(Type t) => Assembly.GetAssembly(t)?.GetReferencedAssemblies().SelectMany(ResolveFromAssemblyName).ToList() ?? new List<Type>(); + + public List<Type> ResolveFromAssemblyName(AssemblyName assemblyName) => ResolveFromAssembly(Assembly.Load(assemblyName)); + + public List<Type> ResolveFromAssembly(Assembly assembly) => assembly.GetTypes() + .Where(x => x is { IsClass: true, IsAbstract: false } && x.GetInterfaces().Contains(typeof(T))).ToList(); +} |