Вопрос
Я попытался создать структуру (SA
), используя [StructLayout(LayoutKind.Explicit)]
, в которой было поле, являющееся другим struct
(SB
).
Во-первых: я был удивлен, что мне разрешили объявить эту другую структуру без [StructLayout(LayoutKind.Explicit)]
, тогда как в SA
все поля должны иметь [FieldOffset(0)]
, иначе компилятор будет кричать. Это не имеет особого смысла.
- Является ли это лазейкой в предупреждениях/ошибках компилятора?
Во-вторых: кажется, что все поля ссылок (object
) в SB
перемещены в начало SB
.
- Где-нибудь описано такое поведение?
- Это зависит от реализации?
- Определено ли где-нибудь, что это зависит от реализации?
:)
Примечание. Я не собираюсь использовать это в рабочем коде. Я задаю этот вопрос в основном из любопытства.
Эксперимент
// No object fields in SB
// Gives the following layout (deduced from experimentation with the C# debugger):
// | f0 | f4 and i | f8 and j | f12 and k | f16 |
[StructLayout(LayoutKind.Explicit)]
struct SA {
[FieldOffset(0)] int f0;
[FieldOffset(4)] SB sb;
[FieldOffset(4)] int f4;
[FieldOffset(8)] int f8;
[FieldOffset(12)] int f12;
[FieldOffset(16)] int f16;
}
struct SB { int i; int j; int k; }
// One object field in SB
// Gives the following layout:
// | f0 | f4 and o1 | f8 and i | f12 and j | f16 and k |
// If I add an `object` field after `j` in `SB`, i *have* to convert
// `f4` to `object`, otherwise I get a `TypeLoadException`.
// No other field will do.
[StructLayout(LayoutKind.Explicit)]
struct SA {
[FieldOffset(0)] int f0;
[FieldOffset(4)] SB sb;
[FieldOffset(4)] object f4;
[FieldOffset(8)] int f8;
[FieldOffset(12)] int f12;
[FieldOffset(16)] int f16;
}
struct SB { int i; int j; object o1; int k; }
// Two `object` fields in `SB`
// Gives the following layout:
// | f0 | f4 and o1 | f8 and o2 | f12 and i | f16 and j | k |
// If I add another `object` field after the first one in `SB`, i *have* to convert
// `f8` to `object`, otherwise I get a `TypeLoadException`.
// No other field will do.
[StructLayout(LayoutKind.Explicit)]
struct SA {
[FieldOffset(0)] int f0;
[FieldOffset(4)] SB sb;
[FieldOffset(4)] object f4;
[FieldOffset(8)] object f8;
[FieldOffset(12)] int f12;
[FieldOffset(16)] int f16;
}
struct SB { int i; int j; object o1; object o2; int k; }