好吧,您必须枚举加载到当前应用程序域的所有程序集中的所有类。为此,您可以在当前应用程序域的 AppDomain 实例上调用 GetAssemblies method。
从那里,您可以在每个 Assembly 上调用 GetExportedTypes(如果您只需要公共类型)或 GetTypes 以获取程序集中包含的类型。
然后,您将在每个 Type 实例上调用 GetCustomAttributes extension method,并传递您希望查找的属性的类型。
您可以使用 LINQ 为您简化:
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>() };
上述查询将为您获取应用了您的属性的每种类型,以及分配给它的属性的实例。
请注意,如果您将大量程序集加载到应用程序域中,则该操作可能会很昂贵。您可以使用Parallel LINQ 来减少操作时间(以 CPU 周期为代价),如下所示:
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>() };
在特定的Assembly 上过滤它很简单:
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>() };
如果程序集中有大量类型,那么您可以再次使用 Parallel LINQ:
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>() };