Ale*_*sov 15
C#不提供动态数组.相反,它提供了以相同方式工作的List类.
要使用列表,请在文件顶部写入:
using System.Collections.Generic;
Run Code Online (Sandbox Code Playgroud)
在你想要使用列表的地方,写(字符串的例子):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Run Code Online (Sandbox Code Playgroud)
如果需要调整数组大小,请查看Array.Resize.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Run Code Online (Sandbox Code Playgroud)
或者,您可以像其他人提到的那样使用List类.如果您提前知道,请确保指定初始大小,以使列表不必在其下调整大小.请参阅初始大小链接的备注部分.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
Run Code Online (Sandbox Code Playgroud)
如果需要List中的数组,可以使用列表中的ToArray()函数.
string[] dinos = dinosaurs.ToArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28602 次 |
| 最近记录: |