C# StructLayout.Explicite Question

J'essaie de comprendre pourquoi le deuxième exemple ci-dessous fonctionne sans problèmes, mais le premier exemple me donne l'exception ci-dessous. Il me semble que les deux exemples devraient vous donner une exception fondée sur la description. Quelqu'un peut-il m'éclairer?

Exception Non Gérée:
Système.TypeLoadException: ne Peut pas
type de charge 'StructTest.OuterType " de
l'assembly 'StructTest, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null'
parce qu'il contient un champ d'objet à
l'offset 0 qui est mal aligné
ou chevauché par un non-objet champ.

au StructTest.Programme.Main(String[]
args) Appuyez sur n'importe quelle touche pour continuer . . .

Exemple 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);
        }
    }
}

Exemple 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);
        }
    }
}

OriginalL'auteur Taylor Leese | 2009-07-25