有什么方法可以在C#中创建动态数组?
有什么方法可以在C#中创建动态数组?
Answers:
看一眼 通用列表。
dynamic[] msdn.microsoft.com/zh-CN/library/dd264736.aspx(动态类型数组)或ExpandoObject msdn.microsoft.com/ zh-cn / library /…我可以-1不用提及这些的答案
用代码示例扩展Chris和Migol的答案。
使用数组
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
使用通用列表。List <T>类在后台使用数组进行存储,但是这样做的方式使其可以有效地增长。
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
有时,普通数组比通用列表更可取,因为它们更方便(例如,对于昂贵的计算,性能更好-例如数字代数应用,或与R或Matlab等统计软件交换数据)
在这种情况下,您可以在动态启动列表之后使用ToArray()方法。
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
当然,只有在数组大小未知或事前不固定的情况下,这才有意义。如果您已经在程序的某个点知道了数组的大小,则最好将其作为固定长度的数组启动。(例如,如果您从ResultSet检索数据,则可以计算其大小并动态启动该大小的数组)
动态数组示例:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
使用实际上是实现数组的数组列表。它最初需要大小为4的数组,并在数组满时会创建一个具有两倍大小的新数组,并将第一个数组的数据复制到第二个数组中,现在将新项插入到新数组中。同样,第二个数组的名称会创建第一个数组的别名,以便可以使用与前一个相同的名称进行访问,并且第一个数组会被处理