可以';t使用C#运行两行三列字符串数组

本文关键字:两行 三列 数组 字符串 使用 可以 运行 | 更新日期: 2023-09-27 18:29:12

我的代码在这里。但我有两个错误。数组初始化程序只能在变量或字段初始化程序中使用。请尝试使用新表达式。

using System;
public class twoDimArray
{
 public static void Main(string[] args)
{
   String[] city=new String[] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };
    for (int i=0; i<2; i++)
    {for (int j=0; j<3; j++)
   {
      System.Console.Write(city[i][j]+"'t");
  }
      System.Console.Write("'n");
  }
 }
}

可以';t使用C#运行两行三列字符串数组

将您的声明更改为

String[,] city = new String[,] { 
                     { "NewYork", "Muscat", "London" }, 
                     { "Cairo", "Beijing", "CapeTown" } };

而不是硬编码的上限,这将是更好的

for (int i = 0; i < city.GetLength(0); i++)
{
    for (int j = 0; j < city.GetLength(1); j++)
    {
        Console.Write(city[i, j] + "'t");
    }
    Console.WriteLine();
}

试试这个

String[,] city=new String[,] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };

试试这个:

String[] city=new String[] { "NewYork","Muscat","London","Cairo","Beijing","CapeTown"  };

而不是:

String[] city=new String[] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };

第二个是错误的,因为您正在初始化一个数组中的另外两个数组。

var city=new List<String[]> {new [] {"NewYork","Muscat","London"} , new []{"Cairo","Beijing","CapeTown"}};

这将创建字符串数组列表,或者此代码将创建二维数组:

String[,] city=new String[,] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };

String[] city=new String[]是一维数组。。。。

use String[,] city=new String[,]()

好吧,这取决于你想要实现的目标。如果是二维数组,您应该使用:

String[,] city = new String[,]{ { "NewYork", "Muscat", "London" }, { "Cairo", "Beijing", "CapeTown" } };

并调用,例如,它是这样的:

System.Console.Write(city[0, 1]);

尽管使用

   string[,] = new string...

可以很好地工作,如果你需要序列化它,我不推荐它。我宁愿使用字符串列表。

 List<object> firstLevel = new List<object>();
 List<string> secondLevel = new List<string>("first", "second", "third");
 firstLevel.Add(secondLevel);
 secondLevel = ("first", "second", "third");
 firstLevel.Add(secondLevel);