获取装配体的所有属性类型(反射

问题描述 投票:1回答:1

我正试图获取汇编中存在的某一类型的所有属性。在我的特殊情况下,我的属性在Controller上,而其他属性在Actions上(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();
c# asp.net-core reflection .net-assembly custom-attributes
1个回答
1
投票

我们没有任何反射方法可以将父类型和它的成员放在一起,所以最好的解决方案是使用以下方法来模拟这种行为。Append 像这样。

var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
var myAttributes = assemblyTypes
    .SelectMany(x => x.GetMethods().Cast<MemberInfo>().Append(x))
    .SelectMany(x => x.GetCustomAttributes<MyAttribute>())
    .Distinct().ToList();
© www.soinside.com 2019 - 2024. All rights reserved.