C # StructLayout. Явный вопрос
Я пытаюсь понять, почему второй пример ниже работает без проблем, но первый пример дает мне исключение ниже. Мне кажется, что оба примера должны дать исключение на основе описания. Кто-нибудь может просветить меня?
Unhandled Exception:
System.TypeLoadException: Could not
load type 'StructTest.OuterType' from
assembly 'StructTest, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null'
because it contains an object field at
offset 0 that is incorrectly aligned
or overlapped by a non-object field.
at StructTest.Program.Main(String[]
args) Press any key to continue . . .
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace StructTest
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct InnerType
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
char[] buffer;
}
[StructLayout(LayoutKind.Explicit)]
struct OuterType
{
[FieldOffset(0)]
int someValue;
[FieldOffset(0)]
InnerType someOtherValue;
}
class Program
{
static void Main(string[] args)
{
OuterType t = new OuterType();
System.Console.WriteLine(t);
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace StructTest
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct InnerType
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
char[] buffer;
}
[StructLayout(LayoutKind.Explicit)]
struct OuterType
{
[FieldOffset(4)]
private int someValue;
[FieldOffset(0)]
InnerType someOtherValue;
}
class Program
{
static void Main(string[] args)
{
OuterType t = new OuterType();
System.Console.WriteLine(t);
}
}
}