C# 返回值
返回值
在上一頁中,我們在所有示例中都使用了 void
關鍵字,這表示方法不應返回值。
如果您希望方法返回一個值,可以使用基本資料型別(如 int
或 double
)代替 void
,並在方法內部使用 return
關鍵字。
示例
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
此示例返回方法中 **兩個引數** 的和
示例
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(5, 3));
}
// Outputs 8 (5 + 3)
您也可以將結果儲存在變數中(推薦,因為這樣更易於閱讀和維護)
示例
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
int z = MyMethod(5, 3);
Console.WriteLine(z);
}
// Outputs 8 (5 + 3)