C#:与Lambda表达式递归函数 [英] C#: Recursive functions with Lambdas

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

问题描述

以下不会编译:

  Func键< INT,INT> FAC = N => (正&下; = 1)? 1:N * FAC(N  -  1);


  

局部变量FAC可能不
  在访问之前进行初始化


如何让一个递归函数与lambda表达式?

[更新]

下面也是,我发现有趣的阅读两个链接:


  1. Eric利珀特的为什么一个递归拉姆达造成一定的分配错误?

  2. 匿名递归在C#


解决方案

功能这种特殊的风格是不是C#支持为单行声明。你必须声明和定义分离成两行

  Func键< INT,INT> FAC = NULL;
FAC = 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天全站免登陆