static int Math(int x, int y)
{
return x + y;
return x * y; // 無法到達,編譯警告 CS0162
}
傳遞陣列參考,方法內修改元素會影響原陣列:
static int Max(int[] arr)
{
int max = arr[0];
for (int i = 1; i < arr.Length; i++)
if (arr[i] > max) max = arr[i];
return max;
}
int[] ns = { 1,2,3,4,5,4,3,2,1 };
Console.WriteLine(Max(ns)); // 5
| 模式 | 語法 | 範例 |
|---|---|---|
| 無參無回傳 | `void M()` | `void SayHi() => Console.WriteLine("Hi");` |
| 有參無回傳 | `void M(T p)` | `void Say(string s) => Console.WriteLine(s);` |
| 有參有回傳 | `T M(T p)` | `int Double(int x) => x * 2;` |
| 表達式主體 (C# 6+) | `=>` | `int Square(int x) => x * x;` |