C#:使用 Lambda 的递归函数 [英] C#: Recursive functions with Lambdas

查看:35
本文介绍了C#:使用 Lambda 的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下不编译:

Funcfac = n =>(n <= 1) ?1 : n * fac(n - 1);

<块引用>

局部变量 'fac' 可能不是访问前初始化

如何使用 lambda 表达式创建递归函数?

[更新]

这里还有两个我觉得有趣的链接:

  1. Eric Lippert 的为什么递归 lambda 会导致明确的赋值错误?"
  2. C# 中的匿名递归

C# 不支持这种特殊样式的函数作为单行声明.你必须把声明和定义分成两行

Funcfac = 空;fac = n =>(n <= 1) ?1 : n * fac(n - 1);

The below does not compile:

Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1);

Local variable 'fac' might not be initialized before accessing

How can you make a recursive function with lambdas?

[Update]

Here are also two links that I found interesting to read:

  1. Eric Lippert's "Why does a recursive lambda cause a definite assignment error?"
  2. Anonymous Recursion in C#

解决方案

This particular style of function is not supported by C# as a single line declaration. You have to separate out the declaration and definition into 2 lines

Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);

这篇关于C#:使用 Lambda 的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆