C# Automatic deep copy of struct

前端 未结 6 1995
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 10:53

I have a struct, MyStruct, that has a private member private bool[] boolArray; and a method ChangeBoolValue(int index, bool Value). <

6条回答
  •  孤街浪徒
    2021-01-17 11:15

    As a workaround, I am going to implement the following.

    There are 2 methods in the struct that can modify the contents of BoolArray. Rather than creating the array when the struct is copied, BoolArray will be created anew when a call to change it is made, as follows

    public void ChangeBoolValue(int index, int value)
    {
        bool[] Copy = new bool[4];
        BoolArray.CopyTo(Copy, 0);
        BoolArray = Copy;
    
        BoolArray[index] = value;
    }
    

    Though this would be bad for any uses that involved much change of the BoolArray, my use of the struct is a lot of copying, and very little changing. This will only change the reference to the array when a change is required.

提交回复
热议问题