C#类获取返回的二维数组

本文关键字:二维数组 返回 获取 | 更新日期: 2024-09-24 06:32:01

我在理解如何使用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类中没有值,它只获取数组的大小。我做错了什么?

C#类获取返回的二维数组

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

老实说,我不知道你的问题是什么,因为我们没有看到你的整个代码。除非你发布完整的解决方案,否则你必须自己想办法。您发布的代码按照您所说的方式运行。

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

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

}

按值复制C#数组

据我所知,阵列上的克隆复制不会应用于您的元素。你必须手动操作。它建议对克隆进行扩展,并让您管理深度复制。