Replace object instance with another in C#

后端 未结 4 1050
长情又很酷
长情又很酷 2021-02-13 05:17

In this question I would like to find out if and how this is possible. This technique would seem extremely bad practice but it seems that the API (UnityEditor) that I am using,

4条回答
  •  孤独总比滥情好
    2021-02-13 06:12

    Since an object state is defined by field values, you can copy memory, containing field values, from one object to another, effectively "replacing" it:

    public static void Replace(T x, T y)
        where T : class
    {
        // replaces 'x' with 'y'
        if(x == null) throw new ArgumentNullException("x");
        if(y == null) throw new ArgumentNullException("y");
    
        var size = Marshal.SizeOf(typeof(T));
        var ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(y, ptr, false);
        Marshal.PtrToStructure(ptr, x);
        Marshal.FreeHGlobal(ptr);
    }
    

    Note that this code requires [StructLayout(LayoutKind.Sequential)] (or LayoutKind.Explicit) attribute defined for a class.

提交回复
热议问题