Properties in a specific order

Using reflection I have a tool that gets class properties:

foreach (MemberInfo member in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
    WriteValue(streamWriter, member.Name);
}

Is there a way to query "GetProperties" to return MemberInfo in the order in which they are defined in the class. I seriously doubt it, but thought I'd ask.

class Person
{
     public int Id { get; set; }
     public int Age { get; set; }
}

I would like to get MemberInfo in this order: Id, Age

+4
source share
2 answers

[ Caution:use your own explanation as this is obviously Microsoft impl information that may change in future versions]

Update : Mono seems to work too

MS, v3.5, :

using System;
using System.Linq;
using System.Reflection;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {    
            typeof(Test).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                .OrderBy(member => member.MetadataToken).ToList()
                .ForEach(member => Console.WriteLine(member.Name));

            Console.ReadLine();
        }
    }

    public class Test
    {
        public int SecondProperty { get; set; }
        public int FirstProperty { get; set; }

    }
}
+2

, - . , getters - , ( ) ( ) , - , , . CLI, , , .

+1

Source: https://habr.com/ru/post/1525555/


All Articles