如何在 C# 中使用 return 语句?
csharpprogrammingserver side programming更新于 2025/7/10 17:37:17
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

