sidristij/dotnetbook

StructLayout example

ZloyChert opened this issue · 1 comments

Возможно, этот пример Вас заинтересует.

    public class CustomClass
    {
        public virtual MyClass Field { get; set; }
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct CustomStructLayoutStruct
    {
        [FieldOffset(0)]
        public CustomClass something;

        [FieldOffset(0)]
        public string str;
    }

    class Program
    {
        static void Main(string[] args)
        {
            CustomStructLayoutStruct customStructLayoutStruct = new CustomStructLayoutStruct();
            customStructLayoutStruct.something = new CustomClass();
            customStructLayoutStruct.str = "4";
            Console.WriteLine($"customStructLayoutStruct.something.GetType(): {customStructLayoutStruct.something.GetType()}");//System.String
            Console.WriteLine($"customStructLayoutStruct.something: {customStructLayoutStruct.something}");//4
            Console.WriteLine($"customStructLayoutStruct.something.Field: {customStructLayoutStruct.something.Field}");//null
            Console.WriteLine($"customStructLayoutStruct.str: {customStructLayoutStruct.str}");//4
        }
    }

Данное поведение наблюдается лишь при виртуальном свойстве.

Не знал что с виртуальными членами работает: я проверю его на partial trust.

  • Partial trust + virtual members union