如何在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

以上是 如何在C#中使用return语句? 的全部内容, 来源链接: utcz.com/z/358184.html

回到顶部