Beh, si dovrebbe enumerare tutte le classi in tutte le assemblee che vengono caricati nel dominio applicazione corrente. Per farlo, chiami lo GetAssemblies
method sull'istanza AppDomain
per il dominio dell'app corrente.
Da lì, si chiama GetExportedTypes
(se si desidera solo i tipi pubblici) o GetTypes
su ogni Assembly
per ottenere i tipi contenuti nell'assieme.
Quindi, chiamaresu ciascuna istanza Type
, passando il tipo di attributo che si desidera trovare.
È possibile utilizzare LINQ per semplificare questo per voi:
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 query sopra si arriva ogni tipo con l'attributo applicato ad esso, insieme con l'istanza dell'attributo (s) assegnato.
Si noti che se è stato caricato un numero elevato di assiemi nel dominio dell'applicazione, tale operazione potrebbe essere costosa. È possibile utilizzare Parallel LINQ per ridurre il tempo dell'operazione, in questo modo:
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>() };
filtrandola su uno specifico Assembly
è semplice:
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>() };
E se il gruppo ha un gran numero di tipi in esso , quindi è possibile utilizzare Parallel LINQ nuovamente:
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>() };
Il collegamento di esempio MSDN è un collegamento morto. – MadTigger