.NET Reflection - 检查类型信息并检索属性性能

Ale*_* Dn 2 .net c# reflection performance attributes

我看过很多关于 .NET 反射性能的文章,并且我知道使用反射调用方法并检索属性值的性能成本很高,而且比直接调用慢大约 2-3 倍。

但是类型信息和属性呢?我知道类型元数据缓存在 .NET 中...所以我认为它不应该增加性能成本,它类似于在字典或列表中搜索(但我不确定)...
检查输入信息以检查属性类型并获取属性类型的自定义属性?

让许多东西基于属性工作是不是不好的实践和设计?

我想要做的是为 ASP.NET 创建一些基础结构,它将检查许多控件和类型的自定义属性,以便检索有关应在页面上注册的所需 JavaScript 文件和客户端代码的信息。

Tet*_*r28 5

构建基于属性的架构并不是一件坏事,但如果你想保持灵活性,你必须引入一个接口/实现来以编程方式独立于属性提供这些信息,并定义一个基于属性的默认实现。

读取属性并不慢,但如果您关心微优化,您可以像这样创建自己的缓存:

static public class Metadata<T>
{
    static public readonly Type Type = typeof(T); //cache type to avoid avcessing global metadata dictionary

    static public class Attribute<TAttribute>
        where TAttribute : Attribute
    {
            static public readonly TAttribute Value = Metadata<T>.Type.GetCustomAttributes(Metadata<TAttribute>.Type).SingleOrDefault() as TAttribute; 
    }
}

//usage
Metadata<MyType>.Attribute<MyAttributeType>.Value; //exception if more then once and null if not defined.
Run Code Online (Sandbox Code Playgroud)