我在理解如何通过get获取我的班级的二维数组时遇到了一些麻烦。
这是我的课程目前正在寻找的方式:
class Something
{
private int[,] xArray;
public Something()
{
xArray = new int[var1, var2];
for (int row = 0; row < xArray.Getlength(0); row++)
for (int col = 0; col < xArray.GetLength(1); col++)
xArray[row, col] = someInt;
}
public int[,] XArray
{
get { return (int[,])xArray.Clone(); }
}
}
class Main
{
Something some;
public void writeOut()¨
{
some = new Something();
for (int row = 0; row < some.XArray.GetLength(0); row++)
for (int col = 0; col < some.XArray.GetLength(1); col++)
Console.Write(some.XArray[row, col].ToString());
}
}
当我用调试器检查时,xArray在Something类中具有它应该具有的所有值,但它在Main类中没有值,它只获得数组的大小。我做错了什么?
答案 0 :(得分:1)
据我所知,数组上的克隆副本不会应用于您的元素。你必须手动完成。它建议对Clone进行扩展,并让您管理深层复制。
答案 1 :(得分:1)
想出这个snipet并在控制台中写出一百“1”,这意味着测试人员(你的“主”)确实看到了正确的值。
完全可靠,我不知道你的问题是什么,因为我们没有看到你的整个代码。除非你发布整个解决方案,否则你必须弄清楚自己。您发布的代码按您所说的方式工作。
长话短说:我添加了运行所需的部分,不仅运行,还没有显示任何错误。您可能希望将您的代码与下面的代码进行比较。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
tester.writeOut();
}
}
class Something
{
private int firstDimensionLenght = 10;
private int secondDimensionLenght = 10;
private int[,] xArray;
public Something()
{
xArray = new int[firstDimensionLenght, secondDimensionLenght];
for (int row = 0; row < xArray.GetLength(0); row++)
for (int col = 0; col < xArray.GetLength(1); col++)
xArray[row, col] = 1;
}
//Add some intellisence information stating you clone the initial array
public int[,] XArrayCopy
{
get { return (int[,])xArray.Clone(); }
}
}
class tester
{
static Something some;
//We dont want to initialize "some" every time, do we? This constructor
//is called implicitly the first time you call a method or property in tester
static tester(){
some = new Something()
}
//This code is painfuly long to execute compared to what it does
public static void writeOut()
{
for (int row = 0; row < some.XArrayCopy.GetLength(0); row++)
for (int col = 0; col < some.XArrayCopy.GetLength(1); col++)
Console.Write(some.XArrayCopy[row, col].ToString());
}
//This code should be much smoother
public static void wayMoreEfficientWriteOut()
{
int[,] localArray = some.XArrayCopy();
for (int row = 0; row < localArray.GetLength(0); row++)
for (int col = 0; col < localArray.GetLength(1); col++)
Console.Write(localArray[row, col].ToString());
}
}
}