How to list all classes with a specific Attet attribute in an assembly?

Please help me on how to list all classes with a specific attribute inside an assembly in C #?

+4
source share
2 answers

I finally wrote my class ClassLoader, which supports .NET 2.0, 3.5, and 4.0.

static class ClassLoader { public static IEnumerable<MethodInfo> GetMethodsWithAttribute(Type attributeType, Type type) { List<MethodInfo> list = new List<MethodInfo>(); foreach (MethodInfo m in type.GetMethods()) { if (m.IsDefined(attributeType, false)) { list.Add(m); } } return list; } public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, string assemblyName) { Assembly assembly = Assembly.LoadFrom(assemblyName); return GetTypesWithAttribute(attributeType, assembly); } public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, Assembly assembly) { List<Type> list = new List<Type>(); foreach (Type type in assembly.GetTypes()) { if (type.IsDefined(attributeType, false)) list.Add(type); } return list; } } 
0
source

Example code that gets all serializable types inside an assembly:

 public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly) { return assembly.GetTypes() .Where(type => type.IsDefined(typeof(SerializableAttribute), false)); } 

The second argument to IsDefined() whether this attribute also accepts base types.

A usage example that finds all types decorated with MyDecorationAttribute :

 public class MyDecorationAttribute : Attribute{} [MyDecoration] public class MyDecoratedClass{} [TestFixture] public class DecorationTests { [Test] public void FindDecoratedClass() { var currentAssembly = Assembly.GetExecutingAssembly(); var typesWithAttribute = GetTypesWithAttribute(currentAssembly); Assert.That(typesWithAttribute, Is.EquivalentTo(new[] {typeof(MyDecoratedClass)})); } public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly) { return assembly.GetTypes() .Where(type => type.IsDefined(typeof(MyDecorationAttribute), false)); } } 
+6
source

Source: https://habr.com/ru/post/1311046/


All Articles