Lambda表达式是一个匿名的方法,在开发期我们是不知道其方法名是什么的,所以我们要怎么递归调用呢?
如果你看过我这文章《让您知道您的方法是被何“人”调用 》的话,你应该会“啊哈”的拍一下头脑,思路就出来了,没错!!就是直接用StackFrame获取当前执行的方法,然后直接Invoke即可。
示例代码:
class Test
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
///
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <param name="num"></param>
/// <param name="total"></param>
/// <returns></returns>
public delegate long AddMethod(long v1, long v2, int num, int cout);
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
///
/// </summary>
/// <param name="addMethod"></param>
/// <param name="cout"></param>
static void Print(AddMethod method, int cout)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine(method(0, 1, 2, cout));
}
![](/Images/OutliningIndicators/InBlock.gif)
static void Main()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
//求0,1,1,2,3,5,8
.类似的数据队列在第30个位置的数
Print((v1, v2, num, cout) =>
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.Write(v1);
Console.Write(",");
![](/Images/OutliningIndicators/InBlock.gif)
num++;
if (num == cout)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.Write(v2);
Console.WriteLine();
return v1 + v2;
}
else
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
//取得当前方法
StackFrame frame = new StackFrame(0);
//递归调用
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
return (long)(frame.GetMethod().Invoke(num, new object[]
{ v2, (v1 + v2), num, cout }));
}
}, 30);
Console.Read();
}
}我们的代码成功运行了
![](/Emoticons/msn/shades_smile.gif)
,成功的求出在第30个位置的数值是:514229
其时,.NET里还有一个东东可以方便的得到当前调用方法的引用,这东东就是
MethodBase,其有一个静态方法GetCurrentMethod 可直接获取当前执行的方法引用,所以我们可以将上面的StackFrame处的两句代码改为如下:
//递归调用
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
return (long)(MethodBase.GetCurrentMethod().Invoke(num, new object[]
{ v2, (v1 + v2), num, cout }));执行后的结果都是一样的
![](/Emoticons/msn/teeth_smile.gif)
(不一样才怪了Orz)