[英]Get all attributes type in assembly (reflection)
我正在嘗試獲取程序集中存在的某種類型的所有屬性。 在我的具體情況下,我在 Controller 上有屬性,在動作 (MVC) 上有其他屬性。 有了這段代碼,我可以得到我想要的,但我很確定有辦法避免聯合
var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
var myAttributes = assemblyTypes
.SelectMany(x => x.GetCustomAttributes<MyAttribute>()).ToList();
myAttributes = myAttributes.Union(assemblyTypes
.SelectMany(x => x.GetMethods())
.SelectMany(x => x.GetCustomAttributes<MyAttribute>())).ToList();
myAttributes = myAttributes.Distinct().ToList();
我們沒有任何反射方法可以將父類型及其成員放在一起,因此最好的解決方案是使用Append
模擬這種行為,如下所示:
var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
var myAttributes = assemblyTypes
.SelectMany(x => x.GetMethods().Cast<MemberInfo>().Append(x))
.SelectMany(x => x.GetCustomAttributes<MyAttribute>())
.Distinct().ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.