与其他在C#替换对象实例 [英] Replace object instance with another in C#
问题描述
在这个问题,我想看看是否和如何这是可能的。这种技术似乎非常不好的做法,但似乎一个API,我使用的是做这样的事情,我只是好奇(UnityEditor)。
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 an API (UnityEditor) that I am using is doing something like this and I am just curious.
如果有多个同一个对象的引用,是有可能实例化一个新的对象到相同的内存插槽使所有前面的引用指向新的对象?
If there are multiple references to the same object, is it possible to instantiate a new object into the same memory slot so that all previous references point to the new object?
我的身影,唯一的这样,这将是是与非托管C ++是可行的。从本质上讲是发生以下内容:
I figure that the only way that this would be feasible would be with unmanaged C++. Essentially the following is happening:
// Original prefab
GameObject prefab = x;
prefab.tag = "Untagged";
// A copy of the original prefab
GameObject prefabCopy = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
prefabCopy.tag = "EditorOnly"; // Change from initial value "Untagged"
Debug.Log(prefab.tag); // "Untagged" - expected
Debug.Log(prefabCopy.tag); // "EditorOnly" - expected
// Replace contents of prefab file with `prefabCopy`
PrefabUtility.ReplacePrefab(prefabCopy, prefab);
// Destroy the copy
DestroyImmediate(prefabCopy);
Debug.Log(prefab.tag); // "EditorOnly" - whoa?
一些如何预制
现在指向不同的对象
的注:记住裸团结是建立在.NET 的
推荐答案
由于对象的状态是由字段值定义,可以有效地复制内存,包含的字段值,从一个对象到另一个取代吧:
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>(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);
}
请注意,此代码需要 [StructLayout(LayoutKind。顺序)]
(或 LayoutKind.Explicit
一类的定义)的属性。
Note that this code requires [StructLayout(LayoutKind.Sequential)]
(or LayoutKind.Explicit
) attribute defined for a class.
这篇关于与其他在C#替换对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!