現在のアプリ ドメインに読み込まれているすべてのアセンブリのすべてのクラスを列挙する必要があります。これを行うには、現在のアプリ ドメインのインスタンスでGetAssemblies
メソッドを呼び出します。AppDomain
そこから、GetExportedTypes
(パブリック タイプのみが必要な場合) またはGetTypes
on eachAssembly
を呼び出して、アセンブリに含まれるタイプを取得します。
次に、各インスタンスでGetCustomAttributes
拡張メソッドを呼び出し、Type
検索する属性の型を渡します。
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>() };