gpt4 book ai didi

C# memcpy 等价物

转载 作者:太空狗 更新时间:2023-10-29 20:02:23 27 4
gpt4 key购买 nike

我有 2 个相同类型的对象,我想将一种状态浅复制到另一种状态。在 C++ 中,我有很棒的 memcpy。我怎样才能在 C# 中做到这一点? MemberwiseClone() 不够好,因为它创建并返回一个新对象,而我喜欢复制到现有对象。我想过使用反射,但我担心它对于生产代码来说太慢了。我还考虑过使用 .Net 序列化程序之一,但我认为它们也创建对象而不是设置现有对象。

我的用例:

我有一个模板对象(类而不是结构)需要由它的一个实例(由这个模板构成的对象)更新

有什么想法吗?

最佳答案

C# 中(在 C++ 中也是如此),“新对象”和“现有对象的副本”之间没有区别,只要它们的所有成员都相等对彼此。

给定:

Int32 a = 5;

,两种操作:

Int32 b = 5;
Int32 b = a;

产生相同的结果。

MSDN reference 中所述:

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object.

If a field is a value type, a bit-by-bit copy of the field is performed.

If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

,即它与 C++

中的 memcpy() 功能相同

关于C# memcpy 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/510971/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com