【问题标题】:How to assign space/null value to a 2D array in C#如何在 C# 中将空格/空值分配给二维数组
【发布时间】:2019-09-15 12:05:45
【问题描述】:

我正在尝试打印一个具有空值的 Int 二维数组。这基本上就像在字符串数组中分配一个空间。

int[,] arr = new int[10, 10];
for (int temp = 0; temp < arr.GetLength(0); temp++)
{
 for (int temp2 = 0; temp2 < arr.GetLength(1); temp2++)
  {
    arr[temp, temp2] = xxxxx ;
   }
}

for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++)
{
  for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++)
   {
    Console.Write(arr[xIndex, yLoop]);
    }
    Console.WriteLine();
}

到目前为止,我尝试分配 null 值,但我得到“无法将 null 转换为 'int',因为它是不可为 null 的值类型。 如果我不分配任何值,它只是简单地输出 0 并且我希望它在控制台中不显示任何内容。

【问题讨论】:

    标签: c# arrays 2d


    【解决方案1】:

    您不能将 NaN 值分配给 int。 int 的每个可能值都是一个数字,如果您希望不显示任何内容而不是 0,则必须以某种方式解决此问题。

    【讨论】:

      【解决方案2】:

      好吧,如果您的二维数组包含空值,只需检查该值是否为空,如果是,则不打印任何内容。这里的问题是您的数组被声明为 int 数组,因此它不能包含 null。
      如果您的实际数组值都是正数,则可能的解决方法是分配负值而不是“null”。这样,您就可以检查该值。

      int[,] arr = new int[10, 10];
      for (int temp = 0; temp < arr.GetLength(0); temp++) {
        for (int temp2 = 0; temp2 < arr.GetLength(1); temp2++) {
          arr[temp, temp2] = xxxxx; // set to -1 if the value is unknown / undefined etc.
        }
      }
      
      for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++) {
        for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++) {
          if (arr[xIndex, yLoop] >= 0) {
            Console.Write(arr[xIndex, yLoop]);
          }
          else {
            Console.Write(" ");
          }
        }
        Console.WriteLine();
      }
      

      【讨论】:

        【解决方案3】:

        您可以尝试将 int 设为可为空的类型,以便您可以将 null 分配给它。这应该是 true 或所有其他值类型,例如 doublebool。只需将int[,] 更改为int?[,]

        【讨论】:

          【解决方案4】:

          如果您只想打印到控制台,只需使用 if 条件打印空格..

          int[,] arr = new int[10, 10]; // 你不需要赋值。默认为 0

          for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++)
          {
            for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++)
             {
              if(arr[xIndex, yLoop]==0)
              {
                 Console.Write(" ");
              }
             }
              Console.WriteLine();
          }
          

          【讨论】:

            【解决方案5】:

            将 int 定义为可空类型将解决您的问题,只需将数组声明为:

            int?[,] arr = new int?[10, 10];

            【讨论】:

              猜你喜欢
              • 2017-01-13
              • 2023-03-06
              • 2018-05-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-03-15
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多