如何在 C# 中使用 return 語句?
return 語句用於返回值。當程式呼叫函式時,程式控制權將轉移到被呼叫的函式。被呼叫的函式執行一個已定義的任務,當其 return 語句被執行或當其函式結束的閉合花括號被觸及時,它將程式控制權返回到主程式。
以下是有關如何在 C# 中使用 return 語句的示例。在此,我們查詢一個數字的階乘並使用 return 語句返回結果。
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;以下是完整示例。
示例
using System;
namespace Demo {
class Factorial {
public int display(int n) {
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}輸出
Value is : 120
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP