gpt4 book ai didi

c# - 正确复制其中包含(字节)数组的 C# 结构?

转载 作者:太空狗 更新时间:2023-10-29 21:15:12 26 4
gpt4 key购买 nike

据我了解,将结构变量分配给另一个结构变量时,通常会复制第一个变量而不是创建引用:

public struct MYSTRUCT1
{
public byte val1;
}
// (...)
public DoSomething() {
MYSTRUCT1 test1;
test1.val1 = 1;
MYSTRUCT1 test2 = test1;
test2.val1 = 2;

Console.WriteLine(test1.val1);
Console.WriteLine(test2.val1);
}

这很好用,输出是:

1
2

但是,如果我的结构中有一个 byte[],这种行为会改变:

public struct MYSTRUCT1
{
public byte[] val1;
}
// (...)
public DoSomething() {
MYSTRUCT1 test1;
test1.val1 = new byte[0x100];
test1.val1[0] = 1;
MYSTRUCT1 test2 = test1;
test2.val1[0] = 2;

Console.WriteLine(test1.val1[0]);
Console.WriteLine(test2.val1[0]);
}

这是输出:

2
2

我怎样才能避免这种情况?我确实需要使用 完整 结构的副本,包括任何字节数组。

谢谢! ♪


编辑:感谢您的帮助!为了深度复制我的结构,我现在使用这段代码:

public static object deepCopyStruct(object anything, Type anyType)
{
return RawDeserialize(RawSerialize(anything), 0, anyType);
}

/* Source: http://bytes.com/topic/c-sharp/answers/249770-byte-structure */
public static object RawDeserialize(byte[] rawData, int position, Type anyType)
{
int rawsize = Marshal.SizeOf(anyType);
if (rawsize > rawData.Length)
return null;
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
object retobj = Marshal.PtrToStructure(buffer, anyType);
Marshal.FreeHGlobal(buffer);
return retobj;
}

/* Source: http://bytes.com/topic/c-sharp/answers/249770-byte-structure */
public static byte[] RawSerialize(object anything)
{
int rawSize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawDatas = new byte[rawSize];
Marshal.Copy(buffer, rawDatas, 0, rawSize);
Marshal.FreeHGlobal(buffer);
return rawDatas;
}

必须这样调用:

MYSTRUCT1 test2 = (MYSTRUCT1)deepCopyStruct(test1, typeof(MYSTRUCT1));

这似乎工作正常,但我知道这是脏代码。

但是,由于我正在使用的结构中有超过 50 个 byte[] 和其他几个结构,因此编写 Copy()/实在是太麻烦了Clone() 方法。

当然欢迎提出更好的代码建议。

最佳答案

您必须创建一个Clone 方法来对结构成员进行深度复制:

public struct MyStruct
{
public byte[] data;
public MyStruct Clone()
{
byte[] clonedData = new byte[this.data.Length];
data.CopyTo(clonedData, 0);

return new MyStruct { data = clonedData };
}
}

关于c# - 正确复制其中包含(字节)数组的 C# 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3537583/

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