使用 ref 和 out 傳遞陣列
如同所有的 out 參數,陣列型別的 out 參數必須先指派才能使用,也就是說,它必須由被呼叫端指派
static void TestMethod1(out int[] arr) { arr = new int[5] { 1, 2, 3, 4, 5 }; // definite assignment of arr }
如同所有的 ref 參數,陣列型別的 ref 參數也必須由呼叫端明確指派。因此就不需要由被呼叫端明確指派。陣列型別的 ref 參數可以變更為呼叫的結果。例如,您可以將 null 值指派給陣列或將陣列初始化為不同的陣列。例如:
static void TestMethod2(ref int[] arr) { if (arr == null) { arr = new int[5]; // arr initialized to a different array } arr[0] = 1111; arr[4] = 5555; }