获得装配所有类型的自定义属性

获得装配所有类型的自定义属性

本文介绍了获得装配所有类型的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种优雅的方式来获得在具有自定义属性的程序集的所有类型?

Is there an elegant way to get all the types in an assembly that have a custom attribute?

所以,如果我有一个类

[Findable]
public class MyFindableClass
{}

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

I would like to be able to find it in a collection of types returned by Assembly.GetTypes(...)

我可以用一个大的邪恶黑客做到这一点,但我敢肯定有人有一个更好的方式。

I can do it with a big vile hack, but I'm sure someone has a nicer way.

推荐答案

我不认为你可以列举闪避组件中的每类型,检查属性,但你可以使用LINQ使查询更易于理解:

I wouldn't think you can dodge enumerating every type in the assembly, checking for the attribute, but you could use LINQ to make the query easier to understand:

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

编辑:从 MemberInfo.GetCustomAttributes 移动到 Attribute.IsDefined 根据马克Gravell的建议

Moved from MemberInfo.GetCustomAttributes to Attribute.IsDefined based on Marc Gravell's suggestion.

这篇关于获得装配所有类型的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:03