Bueno, tendría que enumerar todas las clases en todos los ensamblados que se cargan en el dominio de la aplicación actual. Para hacer eso, llamaría al GetAssembliesmétodo en la AppDomaininstancia para el dominio de la aplicación actual.
Desde allí, llamaría GetExportedTypes(si solo desea tipos públicos) o GetTypesen cada uno Assemblypara obtener los tipos contenidos en el ensamblado.
Luego, llamaría al GetCustomAttributesmétodo de extensión en cada Typeinstancia, pasando el tipo de atributo que desea encontrar.
Puede usar LINQ para simplificar esto para usted:
var typesWithMyAttribute =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
La consulta anterior le proporcionará cada tipo con su atributo aplicado, junto con la instancia de los atributos asignados a él.
Tenga en cuenta que si tiene una gran cantidad de ensamblados cargados en el dominio de su aplicación, esa operación podría ser costosa. Puede usar Parallel LINQ para reducir el tiempo de la operación, así:
var typesWithMyAttribute =
// Note the AsParallel here, this will parallelize everything after.
from a in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
Filtrarlo en un específico Assemblyes simple:
Assembly assembly = ...;
var typesWithMyAttribute =
from t in assembly.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
Y si el ensamblaje tiene una gran cantidad de tipos, puede usar Parallel LINQ nuevamente:
Assembly assembly = ...;
var typesWithMyAttribute =
// Partition on the type list initially.
from t in assembly.GetTypes().AsParallel()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };