陣列型別
在 C# 中,陣列實際上是物件,陣列是一種資料結構,它包含若干相同型別的變數,
陣列概述
陣列具有以下屬性:
- 陣列可以是 一維、 多維或 交錯的,
- 數值陣列元素的默認值設定為零,而參考元素的默認值設定為 null,
- 交錯陣列是陣列的陣列,因此其元素是參考型別并初始化為 null,
- 陣列的索引從零開始:具有 n 個元素的陣列的索引是從 0 到 n-1,
- 陣列元素可以是任何型別,包括陣列型別,
- 陣列型別是從抽象基型別 Array 派生的 參考型別, 由于此型別實作了 IEnumerable 和 IEnumerable< T> ,因此可以對 C# 中的所有陣列使用foreach 迭代,
一維陣列
int[] array = new int[5];
string[] stringArray = new string[6];
此陣列包含從 array[0] 到 array[4] 的元素, new 運算子用于創建陣列并將陣列元素初始化為它們的默認值, 在此例中,所有陣列元素都初始化為零,
陣列初始化
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
多維陣列
陣列可以具有多個維度, 例如,下列宣告創建一個四行兩列的二維陣列,
int[,] array = new int[4, 2];
宣告創建一個三維(4、2 和 3)陣列,
int[, ,] array1 = new int[4, 2, 3];
陣列初始化
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);
// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12
也可以初始化陣列但不指定級別,
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
如果選擇宣告一個陣列變數但不將其初始化,必須使用 new 運算子將一個陣列分配給此變數, 以下示例顯示 new 的用法,
int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
將值分配給特定的陣列元素,
array5[2, 1] = 25;
將陣列元素初始化為默認值(交錯陣列除外):
int[,] array6 = new int[10, 10];
交錯陣列
交錯陣列是元素為陣列的陣列, 交錯陣列元素的維度和大小可以不同, 交錯陣列有時稱為“陣列的陣列”,
int[][] jaggedArray = new int[3][];
必須初始化 jaggedArray 的元素后才可以使用它,
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
每個元素都是一個一維整數陣列, 第一個元素是由 5 個整陣列成的陣列,第二個是由 4 個整陣列成的陣列,而第三個是由 2 個整陣列成的陣列,
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
宣告陣列時將其初始化
int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
訪問個別陣列元素:
// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;
// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;
陣列使用 foreach
創建一個名為 numbers 的陣列,并用 foreach 陳述句回圈訪問該陣列:
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0
多維陣列,可以使用相同方法來回圈訪問元素
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55
一維陣列傳遞給方法
int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);
print 方法的部分實作,
void PrintArray(int[] arr)
{
// Method code.
}
初始化和傳遞新陣列
PrintArray(new int[] { 1, 3, 5, 7, 9 });
官方示例
class ArrayClass
{
static void PrintArray(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
}
System.Console.WriteLine();
}
static void ChangeArray(string[] arr)
{
// The following attempt to reverse the array does not persist when
// the method returns, because arr is a value parameter.
arr = (arr.Reverse()).ToArray();
// The following statement displays Sat as the first element in the array.
System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
}
static void ChangeArrayElements(string[] arr)
{
// The following assignments change the value of individual array
// elements.
arr[0] = "Sat";
arr[1] = "Fri";
arr[2] = "Thu";
// The following statement again displays Sat as the first element
// in the array arr, inside the called method.
System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
}
static void Main()
{
// Declare and initialize an array.
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
// Pass the array as an argument to PrintArray.
PrintArray(weekDays);
// ChangeArray tries to change the array by assigning something new
// to the array in the method.
ChangeArray(weekDays);
// Print the array again, to verify that it has not been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
PrintArray(weekDays);
System.Console.WriteLine();
// ChangeArrayElements assigns new values to individual array
// elements.
ChangeArrayElements(weekDays);
// The changes to individual elements persist after the method returns.
// Print the array, to verify that it has been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
PrintArray(weekDays);
}
}
// Output:
// Sun Mon Tue Wed Thu Fri Sat
// arr[0] is Sat in ChangeArray.
// Array weekDays after the call to ChangeArray:
// Sun Mon Tue Wed Thu Fri Sat
//
// arr[0] is Sat in ChangeArrayElements.
// Array weekDays after the call to ChangeArrayElements:
// Sat Fri Thu Wed Thu Fri Sat
多維陣列傳遞給方法
int[,] theArray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
Print2DArray(theArray);
該方法接受一個二維陣列作為其引數,
void Print2DArray(int[,] arr)
{
// Method code.
}
初始化和傳遞新陣列
Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
官方示例
class ArrayClass2D
{
static void Print2DArray(int[,] arr)
{
// Display the array elements.
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
}
}
}
static void Main()
{
// Pass the array as an argument.
Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8
*/
使用 ref 和 out 傳遞陣列
使用陣列型別的 out 引數前必須先為其賦值,即必須由被呼叫方為其賦值,
static void TestMethod1(out int[] arr)
{
arr = new int[10]; // definite assignment of arr
}
與所有的 ref 引數一樣,陣列型別的 ref 引數必須由呼叫方明確賦值, 因此不需要由接受方明確賦值, 可以將陣列型別的 ref 引數更改為呼叫的結果,
static void TestMethod2(ref int[] arr)
{
arr = new int[10]; // arr initialized to a different array
}
示例
在呼叫方(Main 方法)中宣告陣列 theArray,并在 FillArray 方法中初始化此陣列, 然后將陣列元素回傳呼叫方并顯示,
class TestOut
{
static void FillArray(out int[] arr)
{
// Initialize the array:
arr = new int[5] { 1, 2, 3, 4, 5 };
}
static void Main()
{
int[] theArray; // Initialization is not required
// Pass the array to the callee using out:
FillArray(out theArray);
// Display the array elements:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i] + " ");
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Array elements are:
1 2 3 4 5
*/
在呼叫方(Main 方法)中初始化陣列 theArray,并通過使用 ref 引數將其傳遞給 FillArray 方法, 在 FillArray 方法中更新某些陣列元素, 然后將陣列元素回傳呼叫方并顯示
class TestRef
{
static void FillArray(ref int[] arr)
{
// Create the array on demand:
if (arr == null)
{
arr = new int[10];
}
// Fill the array:
arr[0] = 1111;
arr[4] = 5555;
}
static void Main()
{
// Initialize the array:
int[] theArray = { 1, 2, 3, 4, 5 };
// Pass the array using ref:
FillArray(ref theArray);
// Display the updated array:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i] + " ");
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Array elements are:
1111 2 3 4 5555
*/
隱式型別的陣列
如何創建隱式型別的陣列:
class ImplicitlyTypedArraySample
{
static void Main()
{
var a = new[] { 1, 10, 100, 1000 }; // int[]
var b = new[] { "hello", null, "world" }; // string[]
// single-dimension jagged array
var c = new[]
{
new[]{1,2,3,4},
new[]{5,6,7,8}
};
// jagged array of strings
var d = new[]
{
new[]{"Luca", "Mads", "Luke", "Dinesh"},
new[]{"Karen", "Suma", "Frances"}
};
}
}
創建包含陣列的匿名型別時,必須在該型別的物件初始值設定項中對陣列進行隱式型別化, 在下面的示例中,contacts 是一個隱式型別的匿名型別陣列,其中每個匿名型別都包含一個名為 PhoneNumbers 的陣列, 請注意,物件初始值設定項內部未使用 var 關鍵字,
var contacts = new[]
{
new {
Name = " Eugene Zabokritski",
PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
},
new {
Name = " Hanying Feng",
PhoneNumbers = new[] { "650-555-0199" }
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/49170.html
標籤:C#
上一篇:C#中列舉型別的宣告與使用舉例
