【问题标题】:Get all attributes type in assembly (reflection)获取程序集中的所有属性类型(反射)
【发布时间】: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


【解决方案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();

【讨论】:

  • 感谢您的简化,但是问题询问是否可以避免联合(有利于反射,如果可以这样做,还有代码)。这意味着如果无法避免联合,也会接受否定响应。
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多