C#數(shù)組初始化的三大方法詳解
我們在實際開發(fā)學(xué)習(xí)中經(jīng)常會碰到C#數(shù)組初始化的問題,那么如何實現(xiàn)C#數(shù)組初始化呢,那么根據(jù)不同的風(fēng)格有很多的方法有所選擇,這里就向你介紹C#數(shù)組初始化的三大方法,本示例顯示用三種不同方法初始化不同類型的數(shù)組:一維、多維和交錯。
C#數(shù)組初始化三大方法示例
- // Single-dimensional array (numbers).
- int[] n1 = new int[4] {2, 4, 6, 8};
- int[] n2 = new int[] {2, 4, 6, 8};
- int[] n3 = {2, 4, 6, 8};
- // Single-dimensional array (strings).
- string[] s1 = new string[3] {"John", "Paul", "Mary"};
- string[] s2 = new string[] {"John", "Paul", "Mary"};
- string[] s3 = {"John", "Paul", "Mary"};
- // Multidimensional array.
- int[,] n4 = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
- int[,] n5 = new int[,] { {1, 2}, {3, 4}, {5, 6} };
- int[,] n6 = { {1, 2}, {3, 4}, {5, 6} };
- // Jagged array.
- int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
- int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
- int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
復(fù)制該代碼,并將其粘貼到控制臺應(yīng)用程序的 Main 方法中即可實現(xiàn)編譯代碼。
如果該數(shù)組并未在聲明時初始化,數(shù)組成員將自動被初始化為該數(shù)組類型的默認初始值。如果數(shù)組聲明是某類型的字段,則實例化該類型時,數(shù)組將被設(shè)置為默認值 null。
C#數(shù)組初始化的三大方法和相關(guān)內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C#數(shù)組初始化有所幫助。
【編輯推薦】