【问题标题】:get all types in assembly with custom attribute使用自定义属性获取程序集中的所有类型
【发布时间】:2011-06-18 16:21:31
【问题描述】:

有没有一种优雅的方法来获取程序集中具有自定义属性的所有类型?

如果我有课

[Findable]
public class MyFindableClass
{}

我希望能够在 Assembly.GetTypes(...) 返回的类型集合中找到它

我可以通过一个卑鄙的黑客来做到这一点,但我相信有人有更好的方法。

【问题讨论】:

标签: c# reflection custom-attributes


【解决方案1】:

我认为您无法避免枚举程序集中的每种类型、检查属性,但您可以使用 LINQ 使查询更易于理解:

Assembly assembly = ...
var types = from type in assembly.GetTypes()
            where Attribute.IsDefined(type, typeof(FindableAttribute))
            select type;

编辑:根据 Marc Gravell 的建议,从 MemberInfo.GetCustomAttributes 移至 Attribute.IsDefined

【讨论】:

猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2017-09-19
相关资源
最近更新 更多