【问题标题】:Initializing size of 2D array in runtime using C#使用 C# 在运行时初始化二维数组的大小
【发布时间】:2016-03-16 18:35:49
【问题描述】:

我需要创建一个二维数组,其中列的大小固定为 6,但行的大小可能会有所不同。如何在二维数组中给出动态行大小? 以下是我尝试过但没有成功的代码。

int n;
string num = console.ReadLine();
Int32.TryParse(num,out n);
int[,] ar = new int[n,6] ;

【问题讨论】:

  • 你的代码有什么问题?
  • 你有一个错字:Console 应该大写。 “没有运气”是什么意思?代码编译了吗?更改Console的大小写后,我能够成功运行它。

标签: c# arrays allocation


【解决方案1】:

您构建多维数组的方式没有任何问题。以下代码有效,因此我怀疑您的错误在其他地方:

int n = 9;
int[,] ar = new int[n,6];

我猜您的输入没有正确通过,因此请添加一些错误检查以找出问题所在。首先,Console.ReadLine() 必须大写,否则无法编译。接下来,确保TryParse 实际运行正常(它返回一个bool 表示成功或失败:

int n;
string num = Console.ReadLine();
if (num == null) {
    // ERROR, No lines available to read.
}
if (!Int32.TryParse(num,out n)) {
    // ERROR, Could not parse num.
}
int[,] ar = new int[n,6];

如果问题仍然存在,人们通常更喜欢描述性的解释,而不是“我试过了,但没有运气。”确保告知查看您问题的人这是编译错误或运行时错误,并尽可能具体。

【讨论】:

    【解决方案2】:

    我会使用字典。

    Dictionary<int,List<int>> numbers = new Dictionary<int,List<int>>();
    

    你可以像这样添加一个项目:

    numbers.Add(1,new List<int>(){1,2,3,4,5,6});
    

    并将数字添加到特定行。

    numbers[1].Add(7);
    

    并访问特定行和列中的数字。

    numbers[1][2] = 34;
    

    【讨论】:

    • 集合类很棒,但 Dictionary 会比大多数其他解决方案涉及更多的开销。
    • 没错,对于这个相当不寻常的请求,这只是我想到的第一件事。
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2014-04-16
    • 2023-04-11
    • 2018-03-04
    • 1970-01-01
    • 2015-03-03
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多