初始化字符串数组的选项

在初始化 string[]对象时我有什么选项?

183158 次浏览
string[] str = new string[]{"1","2"};
string[] str = new string[4];

你有几个选择:

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"; // ...

基础:

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();