2017-06-04 79 views
0

使用二维数组:如何在VB中创建同一个数组的新实例?

Public Shared Cells1 As Boolean(,) 
Public Shared Cells2 As Boolean(,)
如何将Cells2等于Cells1但作为新实例? (所以如果我修改Cells2,Cells1不会受到影响。)
Cells2 = Cells1
将两个数组设置为同一个实例,
Cells2 = New Boolean(,) {Cells1}
给我一个语法错误,而
Cells2 = New Boolean(,) {} 
Cells2 = Cells1
就像第一个字符串。

我如何才能按预期工作?提前致谢。
〜尼克

+2

您需要包括为什么要做到这一点,更多的代码,以便我们可以复制你在做什么更多的描述。您可能会看到其他选择。在编程中很少有一种实现方法。 –

+0

[如何制作我的列表的深层副本]的可能重复(https://stackoverflow.com/questions/37085357/how-to-make-a-deep-copy-of-my-list) - 代码在我的答案是普遍的,所以它适用于每个可序列化的对象,而无需更改任何内容。 –

回答

0

也许这

Array.Copy(源,目标,destination.length)

,这将创造浅拷贝。这里的作品:

Module arraycopy 
     Sub Main() 
      Dim xArr(,) As Integer 
      Dim yArr(,) As Integer 
      Dim i, j As Integer 

      ReDim Preserve xArr(10,10) 


      For i = 0 To 10 
       For j = 0 To 10 
        xArr(i,j) = i 
       Next j 
      Next i 

      xArr(0,0) = 42 

      ReDim Preserve yArr(xArr.getLength(0)-1,xArr.getLength(1)-1) 
      Array.Copy(xArr, yArr, yArr.Length) 

      xArr(1,0) = 42 

      For i = 0 To 10 
       For j = 0 To 10 
        Console.WriteLine("Element({0}) = {1}", j, yArr(i,j)) 
       Next j 
      Next i 
      Console.ReadKey() 
     End Sub 
    End Module 

这将工作,考虑到两个阵列具有相同的尺寸。 或者也许用于/ foreach循环和重写数组,如果它不是太大?

0

Array.Clone可以使浅表副本:

Cells2 = CType(Cells1.Clone, Boolean(,)) 
0

你需要的是深刻的克隆。一个新的对象需要实例化并填充数据。建议使用名单的AddRange &:

Class payload 
    Dim payloadData as list(Of list(Of Boolean)) 
    Sub new(optional deepCloneFrom as payload = nothing) 
     payloadData = new list(Of list(Of Boolean)) 
     if deepCloneFrom isnot nothing then 
     for i as integer = 0 to deepCloneFrom.count - 1 
     payloadData.add(new list(of Boolean)) 
     payloadData(i).addRange(deepCloneFrom(i)) 
     next 
     end if 
    end sub 
    End Class 
相关问题