在C#中實現三維數組的深拷貝可以通過以下步驟完成:
下面是一個簡單的示例代碼來實現三維數組的深拷貝:
using System;
class Program
{
static void Main()
{
int[,,] originalArray = new int[2, 2, 2] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
int[,,] newArray = DeepCopy3DArray(originalArray);
// 打印新數組中的值
for (int i = 0; i < newArray.GetLength(0); i++)
{
for (int j = 0; j < newArray.GetLength(1); j++)
{
for (int k = 0; k < newArray.GetLength(2); k++)
{
Console.Write(newArray[i, j, k] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
static int[,,] DeepCopy3DArray(int[,,] originalArray)
{
int[,,] newArray = new int[originalArray.GetLength(0), originalArray.GetLength(1), originalArray.GetLength(2)];
for (int i = 0; i < originalArray.GetLength(0); i++)
{
for (int j = 0; j < originalArray.GetLength(1); j++)
{
for (int k = 0; k < originalArray.GetLength(2); k++)
{
newArray[i, j, k] = originalArray[i, j, k];
}
}
}
return newArray;
}
}
在上面的示例中,DeepCopy3DArray
方法實現了對三維數組的深拷貝操作。通過逐個復制原始數組的元素到新數組中,實現了對原始數組的深拷貝。