1

我看过很多关于 .NET 反射性能的文章,我知道使用反射调用方法和检索属性值的性能代价很高,而且它比直接调用慢 2 到 3 倍。

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

根据属性使许多事情起作用是不好的做法和设计吗?

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

4

2 回答 2

4

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

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

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.
于 2015-01-06T08:08:18.637 回答
2

如果您直接分析您的用例,您将获得最佳答案。毕竟,一点反思也不错。很多反思都可以。使用Stopwatch课程来计时您的替代方案。

于 2013-07-29T20:52:46.877 回答