Index特性未被子类继承,GetProperties返回属性顺序不符合预期
问题:GetProperties()返回的属性顺序不符合Index特性预期
已更新代码:
public class UpdateProductTemplate { [Index(0)] public string ProductID { get; set; } [Index(2)] public string ProductName { get; set; } [Index(3)] public string ShortDescription { get; set; } } public class UpdateProductTemplateWithPrice: UpdateProductTemplate { // For PRICE Updates! [Index(4)] public double? SitePrice { get; set; } [Index(5)] public double? ListPrice { get; set; } [Index(6)] public double? WebSitePrice { get; set; } } List<UpdateProductTemplateWithPrice> Products = new List<UpdateProductTemplateWithPrice>() { new UpdateProductTemplateWithPrice { ProductID = "123", ProductName = "Test Product", ShortDescription = "Test", SitePrice = 123.00, ListPrice = 123.00, WebSitePrice = 123.00 } }; Type type = products.ToArray()[0].GetType(); PropertyInfo[] properties = type.GetProperties(); for (int i = 0; i < properties.Length; i++) { var cell = headerRow.CreateCell(i); cell.SetCellValue(properties[i].Name); }
调用GetProperties()时,返回的数组中SitePrice排在首位,但期望ProductID位于属性数组的第一位。已为子类中的属性设置了更高的Index值,本以为调用GetProperties()时ProductID会排在首位,但并未生效。
原因
Type.GetProperties()的默认返回顺序无固定规则,不会自动识别并遵循Index特性排序。默认情况下通常先返回子类属性,再返回父类属性,但这由CLR实现决定,不能依赖。
解决方法
手动提取属性的Index特性值,按值排序后再使用:
// 获取所有公开实例属性(包括继承自父类的) PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 按Index特性的值从小到大排序 var sortedProperties = properties.OrderBy(p => { var indexAttr = p.GetCustomAttribute<IndexAttribute>(); // 无Index特性的属性放到最后 return indexAttr?.Index ?? int.MaxValue; }).ToArray(); // 使用排序后的属性创建表头 for (int i = 0; i < sortedProperties.Length; i++) { var cell = headerRow.CreateCell(i); cell.SetCellValue(sortedProperties[i].Name); }
注意事项
- 确保
IndexAttribute是你项目中正确的特性(如果是自定义特性,要保证能通过GetCustomAttribute正确获取) - 若有未标记
Index的属性,上述代码会将它们排在末尾,可根据需求调整默认排序值
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

