1. 程式人生 > >c#清空數組&初始化數組&動態數組

c#清空數組&初始化數組&動態數組

pan for line str ima -c system range count

清空數組>>>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

c#清空數組&初始化數組&動態數組