【问题标题】:Using reflection to order properties is slow使用反射来排序属性很慢
【发布时间】:2014-12-04 20:28:07
【问题描述】:

我正在使用this solution 创建一个 OrderAttribute 来订购我的属性。输出是我所期望的,但现在我已经分析了代码,我意识到 GetCustomAttributes 被调用的次数比我想要的要多。对我来说优化性能的最佳方法是什么?

var ordFunc = new Func<System.Reflection.PropertyInfo, int>(p => ((OrderAttribute) p.GetCustomAttributes(typeof (OrderAttribute), false)[0]).Order);
foreach (var obj in objects)
{
    fileWriter.WriteLine(String.Join(",", obj.GetType().GetProperties().OrderBy(ordFunc).Select(x => x.GetValue(obj).ToString())));
}

【问题讨论】:

  • 你只需要在一些静态List中缓存property和attribute的信息,就可以更快地工作了

标签: c# reflection properties


【解决方案1】:

关于谢尔盖的提示。

var ordFunc = new Func<System.Reflection.PropertyInfo, int>(p => ((OrderAttribute) p.GetCustomAttributes(typeof (OrderAttribute), false)[0]).Order);

if(!objects.Any())
    return;

var properties = objects.First().GetType().GetProperties()
    .OrderBy(ordFunc)
    .ToArray();

foreach (var obj in objects)
{
    fileWriter.WriteLine(String.Join(",", properties.Select(x => x.GetValue(obj).ToString())));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2013-07-01
    • 1970-01-01
    • 2010-12-10
    • 2020-06-15
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多