【发布时间】:2020-08-24 23:52:46
【问题描述】:
我正在尝试获取程序集中存在的某种类型的所有属性。在我的具体情况下,我在控制器上有属性,在动作(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();
【问题讨论】:
-
使用Union有什么问题?作为替代,可以使用 Concat 吗?
-
我想知道是否可以在没有联合的情况下通过反射来完成。当我使用 GetMethods 时,我可以获得所有动作的属性,但不能获得控制器和继承的控制器上存在的属性。例如 .SelectMany(x => x.GetMethodsPlusControllers())
标签: c# asp.net-core reflection .net-assembly custom-attributes