使用反射对属性进行排序很慢

本文关键字:排序 属性 反射 | 更新日期: 2023-09-27 18:33:06

我正在使用此解决方案创建一个 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())));
}

使用反射对属性进行排序很慢

关于谢尔盖的提示。

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())));
}