Skip to main content
 首页 » 编程设计

c#之如何在没有引用的情况下正确克隆多维数组

2024年08月12日44exmyth

我的程序中有 3 维数组。我想调试其中的值,然后将这个数组放入另一个数组中,我想在其中找到不同之处。

我试过这个:

Weights weights = new Weights(); // init inside 
List<Weights> weightsDebug = new List<Weigts>(); 
weightsDebug.Add(weights); // I'd put first weigths into the list  
for(int i = 0; i < 100; i++) { 
    // do some bad things with weights; 
    weightsDebug.Add(weights); 
} 

在那之后,我在 weigthsDebug 的所有 99 个元素中得到了相同的权重值。我曾尝试调试,但我意识到,weigts 数组正在更改。我知道问题出在引用文献中(按链接复制,而不是按值复制)——所有推送到 weightsDebug 数组元素都与主循环中的 weights 链接。

我用谷歌搜索了一下,找到了一些复制一维数组的方法。接下来我尝试了:

我将 Clone 方法添加到我的权重类中:

double[][][] values; 
public Weights Clone() { 
    Weights clone = new Weights(); 
    clone.values = (double[][][]) this.values.Clone(); 
    return clone; 
} 
 
public Weights() 
{ 
    Console.WriteLine("Constructor WITHOUT arguments fired"); 
} 

现在我在复制权重时这样做:

Weights weights = new Weights(); // init inside 
List<Weights> weightsDebug = new List<Weigts>(); 
weightsDebug.Add(weights); // I'd put first weigths into the list  
for(int i = 0; i < 100; i++) { 
    // do some bad things with weights; 
    Weights weightsClone = weights.Clone(); 
    weightsDebug.Add(weightsClone); 
} 

而且我仍然在整个调试数组中获取最后更改的值。我该如何纠正它?

请您参考如下方法:

您在这里真正需要的是深度克隆,而不是您目前正在实现的浅层克隆。

很久以前,我们意识到通过创建类 Serializable , 我们可以使用 .Net serialization快速、轻松、正确地深度克隆任何对象的类。

这是我们用于此深度克隆的方法(还有一个使用 DataContractSerializer 的 SilverLight 变体):

    /// <summary> 
    /// This method clones all of the items and serializable properties of the current collection by  
    /// serializing the current object to memory, then deserializing it as a new object. This will  
    /// ensure that all references are cleaned up. 
    /// </summary> 
    /// <returns></returns> 
    /// <remarks></remarks> 
    public T CreateSerializedCopy<T>(T oRecordToCopy) 
    { 
        // Exceptions are handled by the caller 
 
        if (oRecordToCopy == null) 
        { 
            return default(T); 
        } 
 
        if (!oRecordToCopy.GetType().IsSerializable) 
        { 
            throw new ArgumentException(oRecordToCopy.GetType().ToString() + " is not serializable"); 
        } 
 
        var oFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
 
        using (var oStream = new MemoryStream()) 
        { 
            oFormatter.Serialize(oStream, oRecordToCopy); 
            oStream.Position = 0; 
            return (T)oFormatter.Deserialize(oStream); 
        } 
    } 

要使用它,首先确保 Weights 类标记有 Serializable 属性:

[Serializable] 
public class Weights 

然后你可以根据需要克隆:

        var weights = new List<Weights>(); 
        weights.Add(new Weights()); 
 
        var debugWeights = CreateSerializedCopy<List<Weights>>(weights); 
 
        if (debugWeights[0] == weights[0]) 
        { 
            System.Diagnostics.Debug.WriteLine("Did not serialize correctly"); 
        }