StructLayoutAttribute
with the parameter LayoutKind.Sequential
. This forces the compiler to place the fields in unmanaged memory in the order declared in the code. After that, we will sort the reflected fields by offset from the beginning of the class using the Marshal.OffsetOf
method. [StructLayout(LayoutKind.Sequential)] public class TestClass1 { public int Value1; public string Value2; public bool Value3; }
Type type = typeof(TestClass1); List<FieldInfo> fields = new List<FieldInfo>(type.GetFields()); // foreach (FieldInfo field in fields) Console.WriteLine(field.Name); Console.WriteLine(); // ( ) fields.Sort( delegate(FieldInfo _first, FieldInfo _second) { int first = _first.FieldType.GetHashCode(); int second = _second.FieldType.GetHashCode(); return first.CompareTo(second); } ); foreach (FieldInfo field in fields) Console.WriteLine(field.Name); Console.WriteLine(); // fields.Sort( delegate(FieldInfo _first, FieldInfo _second) { int first = Marshal.OffsetOf(type, _first.Name).ToInt32(); int second = Marshal.OffsetOf(type, _second.Name).ToInt32(); return first.CompareTo(second); } ); foreach (FieldInfo field in fields) Console.WriteLine(field.Name); Console.WriteLine();
Source: https://habr.com/ru/post/201584/
All Articles