C# Class 获取返回二维数组

C# Class get returning two dimensional array

我在理解如何使用 get 从我的 class 中获取二维数组时遇到一些麻烦。

这是我的 classes 目前的样子:

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 class 中的所有值,但它在 Main class 中没有值,它只获取数组的大小.我做错了什么?

C# Copy Array by Value

据我了解,数组上的克隆副本不会应用于您的元素。你必须手动完成。它建议做克隆的扩展,让你管理深拷贝。

想出了这个片段,它在控制台中写出了一百个“1”,这意味着测试人员(您的 "Main")确实看到了正确的值。

老实说,我不知道你的问题是什么,因为我们没有看到你的完整代码。除非你 post 你的整个解决方案,否则你必须自己弄清楚。您 post 编辑 的代码确实 按照您所说的方式工作。

长话短说:我添加了 运行 所需的部分,不仅如此 运行,它没有显示任何错误。您可能想将您的代码与下面的代码进行比较。

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());
    }

}


}