根据基类和属性顺序对属性进行排序

时间:2016-04-07 18:55:16

标签: c# asp.net

我正在努力完成这项工作

public class BaseClass
{
    public int baseint { get; set; }
}

public class Dervied : BaseClass
{
    public int Derviedint { get; set; }
}

public class DemoClass : Dervied
{
    [Test(order=2)]
    public int Demoint { get; set; }

    [Test(order=1)]
    public string Demostring { get; set; }
}

现在我想要排序顺序的属性列表 List<PropertyInfo> sorted = List<PropertyInfo>()。现在这个列表应该包含 以下

  • Baseint
  • Derviedint
  • Demostring
  • Demoint

List<PropertyInfo> info = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();

这给了我一个属性列表。但不完全是我想要的。 这是在运行时发送的对象。 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

您可以抓取BaseType上的DemoClass列表,检查DeclaringType的{​​{1}}属性,然后获取PropertyInfo来执行此操作属性:

Test

您可以使用DeclaredOnly flag并按顺序获取每个类的属性,但我认为这种方式更容易理解。

答案 1 :(得分:0)

这是一个稍微扩展的例子 - 你可以根据需要将其压缩一些,但在这种形式下,它会更容易看到发生了什么。

var o = new DemoClass();
var properties = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
var propertiesWithAttributes = 
    properties.Select(property => 
        new
        {
            Property = property,
            Attribute = property.GetCustomAttributes<TestAttribute>().FirstOrDefault()
        });
var sorted =
    propertiesWithAttributes
    .OrderBy(pwa => pwa.Attribute != null ? pwa.Attribute.order : int.MaxValue);