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

标签 c# arrays reference copy struct

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

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/

相关文章:

c# - 难以将 mvc 模型绑定(bind)到 JSON post

c# - 如何从 C# 字符串中按名称查找文本框控件?

c# - 在 Asp.Net MVC 中使用 JsTree 延迟加载 TreeView

Java:自定义对象引用数组

c# - 插入数据库的日期变为 0000

arrays - Rust向量(`Vec<T>`)与数组(`[T; n]`的性能

arrays - 如何将 ActiveRecord 结果转换为哈希数组

arrays - 如何搜索 PowerShell 对象数组并检索匹配字符串的索引?

c++ - 关于 boost::shared_ptr 的困惑

java - Java中的实例变量是通过引用传递的吗?