简体   繁体   English

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

[英]Using reflection to order properties is slow

I'm using this solution to create an OrderAttribute to order my properties. 我正在使用此解决方案创建一个OrderAttribute来对我的属性进行排序。 The output is what I expect, but now that I have profiled the code, I am realizing that GetCustomAttributes is being called way more times than I would like. 输出是我所期望的,但是现在我已经分析了代码,我意识到GetCustomAttributes被调用的次数比我想要的要多。 What would be the best way for me to optimize this for performance? 对我而言,优化性能的最佳方法是什么?

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

Regarding to Sergey's tip. 关于谢尔盖的小费。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM