📜 ⬆️ ⬇️

The order of the fields in accordance with the order in the code (C #)

When working with Reflection, the order of the reflected fields is not guaranteed. This usually does not matter, but sometimes order is needed in exact correspondence to the order defined in the code. For example, it may be necessary for partial serialization.
To solve this contrived problem, we use the services of interlanguage interaction.



First, we mark the class with the attribute 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.
')
Sample test class:
 [StructLayout(LayoutKind.Sequential)] public class TestClass1 { public int Value1; public string Value2; public bool Value3; } 


Example of sorting reflected fields:
  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(); 


In what cases might you need this? Frankly, in very rare. It is not recommended to write any code that depends on the order, but still it happens when it can be useful:

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


All Articles