要實現C#三維數組的深拷貝,可以使用循環遍歷原數組,逐個復制元素到新數組中。以下是一個示例代碼:
public static T[][][] DeepCopy3DArray<T>(T[][][] original)
{
int firstDimension = original.Length;
int secondDimension = original[0].Length;
int thirdDimension = original[0][0].Length;
T[][][] copy = new T[firstDimension][][];
for (int i = 0; i < firstDimension; i++)
{
copy[i] = new T[secondDimension][];
for (int j = 0; j < secondDimension; j++)
{
copy[i][j] = new T[thirdDimension];
for (int k = 0; k < thirdDimension; k++)
{
copy[i][j][k] = original[i][j][k];
}
}
}
return copy;
}
使用這個方法可以對三維數組進行深拷貝,保證新數組和原數組之間沒有引用關聯,修改一個數組不會影響另一個數組。