初始化字符串数组的选项

时间:2009-10-01 16:05:03

标签: c# arrays initialization

初始化string[]对象时,我有哪些选项?

4 个答案:

答案 0 :(得分:148)

您有几种选择:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

答案 1 :(得分:15)

基本:

string[] myString = new string[]{"string1", "string2"};

string[] myString = new string[4];
myString[0] = "string1"; // etc.

高级: 从列表中

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

来自StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();

答案 2 :(得分:2)

string[] str = new string[]{"1","2"};
string[] str = new string[4];

答案 3 :(得分:2)