`Type.GetProperties` property order

后端 未结 5 1936
一生所求
一生所求 2020-12-09 16:13

Short Version

The MSDN documentation for Type.GetProperties states that the collection it returns is not guaranteed to be in alphabetical or declara

5条回答
  •  被撕碎了的回忆
    2020-12-09 16:40

    I use custom attributes to add the necessary metadata myself (it's used with a REST like service which consumes and returns CRLF delimited Key=Value pairs.

    First, a custom attribute:

    class ParameterOrderAttribute : Attribute
    {
        public int Order { get; private set; }
        public ParameterOrderAttribute(int order)
        {
            Order = order;
        }
    }
    

    Then, decorate your classes:

    class Response : Message
    {
        [ParameterOrder(0)]
        public int Code { get; set; }
    }
    
    class RegionsResponse : Response 
    {
        [ParameterOrder(1)]
        public string Regions { get; set; }
    }
    
    class HousesResponse : Response
    {
        public string Houses { get; set; }
    }
    

    A handy method for converting a PropertyInfo into a sortable int:

        private int PropertyOrder(PropertyInfo propInfo)
        {
            int output;
            var orderAttr = (ParameterOrderAttribute)propInfo.GetCustomAttributes(typeof(ParameterOrderAttribute), true).SingleOrDefault();
            output = orderAttr != null ? orderAttr.Order : Int32.MaxValue;
            return output;
        }
    

    Even better, write is as an extension:

    static class PropertyInfoExtensions
    {
        private static int PropertyOrder(this PropertyInfo propInfo)
        {
            int output;
            var orderAttr = (ParameterOrderAttribute)propInfo.GetCustomAttributes(typeof(ParameterOrderAttribute), true).SingleOrDefault();
            output = orderAttr != null ? orderAttr.Order : Int32.MaxValue;
            return output;
        }
    }
    

    Finally you can now query your Type object with:

            var props = from p in type.GetProperties()
                        where p.CanWrite
                        orderby p.PropertyOrder() ascending
                        select p;
    

提交回复
热议问题