C# 利用傳參考取得整個陣列元素

剛好遇到一個有趣的問題,記錄一下。

問題:是否可以利用傳參考 (call by reference) 的方式取得整個陣列元素?舉例來說,現在有一個陣列為 [1, 2, 3, 4, 5],是否可以 ref 傳入 3 然後取得整個陣列?

碰上這個問題,直覺就是利用指標的方式去取。

需要注意的是,下面這段程式碼需要先設專案屬性將 unsafe 開啟,開啟位置為專案 > 屬性 > 建置 > 容許 unsafe 程式碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arrayS = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arrayT = GetArray(param: ref arrayS[4]);
Console.WriteLine(string.Join(",", arrayT));
Console.ReadKey();
}

static int[] GetArray(ref int param)
{
List<int> result = new List<int>();
unsafe
{
fixed (int* p = &param)
{
int* p2 = p;
while (*p2 != 0)
{
result.Add(*p2++);
}
}
}
return result.ToArray();
}
}
}

當然,這段程式碼仍然存在一個問題,也就是在 while (*p2 != 0) 這部分。當陣列結束之後的元素不一定會是為 0,且若陣列存在 0 的元素也會導致結果不如預期,因此較保險的方式還是輸入要取得的長度,或是再找其它方式來判斷結束。