上QQ阅读APP看书,第一时间看更新
Creating Local Functions
Functions that are created within a function are known as Local Functions. These are mainly used when defining helper functions that have to be in the scope of the function itself. The following example shows how the factorial of the number can be obtained by writing a Local Function and calling it recursively:
static void Main(string[] args) { Console.WriteLine(ExecuteFactorial(4)); } static long ExecuteFactorial(int n) { if (n < 0) throw new ArgumentException("Must be non negative",
nameof(n)); else return CheckFactorial(n); long CheckFactorial(int x) {
if (x == 0) return 1; return x * CheckFactorial(x - 1); } }