相关疑难解决方法(0)

使用IsDefined而不是GetCustomAttributes有什么好处

考虑一个程序集包含一个或多个属于自定义属性的类型的情况,MyAttribute您需要获取这些类型的列表.除了更紧凑的语法之外,使用IsDefined与GetCustomAttributes有什么好处?是否暴露/隐藏了另一个没有的东西?一个比另一个更有效吗?

以下是演示每种用法的代码示例:

Assembly assembly = ...
var typesWithMyAttributeFromIsDefined = 
        from type in assembly.GetTypes()
        where type.IsDefined(typeof(MyAttribute), false)
        select type;

var typesWithMyAttributeFromGetCustomAttributes = 
        from type in assembly.GetTypes()
        let attributes = type.GetCustomAttributes(typeof(MyAttribute), false)
        where attributes != null && attributes.Length > 0
        select type;
Run Code Online (Sandbox Code Playgroud)

c# reflection attributes

4
推荐指数
1
解决办法
1503
查看次数

标签 统计

attributes ×1

c# ×1

reflection ×1