c#清空数组&初始化数组&动态数组

清空数组>>>Array.Clear [去MSDN查看]

1 string[] str = new string[2];
2 for (int i = 0; i < str.Length; i++)
3     str[i] = i.ToString();
4 Array.Clear(str, 0, str.Length);
5 for (int i = 0; i < str.Length; i++)
6     Console.WriteLine(string.IsNullOrEmpty(str[i]) ? "null" : str[i]);
7 //输出结果:
8 //null
9 //null

初始化数组>>>Initialize [去MSDN查看]

只是用于初始化,如果数组子项已经被初始化,那么不会改变它的值.(删除下面代码 x[1] = 6; 试试)

 1 int[] x = new int[2];
 2 int[] y = new int[2];
 3 x[0] = 5; x[1] = 6;
 4 x.Initialize();
 5 y.Initialize();
 6 for (int i = 0; i < x.Length; i++)
 7     Console.WriteLine("x:{0}  y:{1}", x[i], y[i]);
 8 //输出结果:
 9 //x:5   y:0
10 //x:6   y:0

动态修改数组大小>>>Array.Resize [去MSDN查看]

处理流程是:先创建一个新的数组,然后把旧数组赋值过去.

 1 int[] x = new int[2];
 2 x[0] = 5; x[1] = 6;
 3 Array.Resize(ref x, x.Length + 2);
 4 for (int i = 0; i < x.Length; i++)
 5     Console.WriteLine("x[{0}]={1}",i, x[i]);
 6 //输出结果:
 7 //x[0]=5
 8 //x[1]=6
 9 //x[2]=0
10 //x[3]=0

如果数组较大,性能影响明显,建议用List<>的AddRange方法. [去MSDN查看]

 1 List<int> lst = new List<int>();
 2 lst.Add(3); lst.Add(4);
 3 int[] x = new int[2];
 4 x[0] = 5; x[1] = 6;
 5 lst.AddRange(x);
 6 for (int i = 0; i < lst.Count; i++)
 7     Console.WriteLine("lst[{0}]={1}", i, lst[i]);
 8 //输出结果:
 9 //lst[0]=3
10 //lst[1]=4
11 //lst[2]=5
12 //lst[3]=6

关于Array数组复制拷贝,倒叙,排序等,详情参见MSDN

posted @ 2017-06-19 18:30  JustXIII  阅读(65210)  评论(0编辑  收藏  举报