0

我的代码在这里。但我得到两个错误。数组初始化器只能用于变量或字段初始化器。尝试改用新表达式。

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");
  }
 }
}
4

6 回答 6

4

将您的声明更改为

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();
}
于 2013-08-28T06:58:59.980 回答
2

尝试这个

String[,] city=new String[,] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };
于 2013-08-28T06:59:02.230 回答
1

尝试这个:

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

代替:

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

第二个是错误的,因为您要在一个数组中初始化 2 个其他数组。

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

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

String[,] city=new String[,] { {"NewYork","Muscat","London"} ,{"Cairo","Beijing","CapeTown"}  };
于 2013-08-28T06:57:22.213 回答
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);
于 2013-08-28T07:04:56.640 回答
1

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

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

于 2013-08-28T06:58:58.130 回答
1

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

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

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

System.Console.Write(city[0, 1]);
于 2013-08-28T07:00:36.770 回答