foreach中的函数调用了几次?

博客通过C#代码示例,探讨了foreach和for循环中函数的调用次数。代码定义了GetTheDatas函数,在嵌套循环中调用该函数,最后输出函数调用次数,帮助理解循环中函数调用的机制。
前段时间遇到了这样一个问题,下面的这段代码:
None.gifusing System;
None.gif
None.gif
class test
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private static int inNumber = 0;
InBlock.gif    
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
int[] tt = GetTheDatas();
InBlock.gif        
foreach(int i in  GetTheDatas())
InBlock.gif            
foreach(int j in  GetTheDatas())
InBlock.gif                
foreach(int k in GetTheDatas())
InBlock.gif                    Console.WriteLine(i
*j*k);
InBlock.gif        Console.ReadLine();
InBlock.gif        Console.WriteLine(inNumber);    
//这里输出多少?
InBlock.gif
        Console.ReadLine();
InBlock.gif        
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private static int[] GetTheDatas()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        inNumber
++;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
return (new int[]dot.gif{1,2,3});    
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
不用编译工具,猜测一下有注释的地方输出结果是多少?
我们先来看一for循环的输出:
None.gifusing System;
None.gif
None.gif
class test
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private static int inNumber = 0;
InBlock.gif    
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
int[] tt = GetTheDatas();
InBlock.gif        
for(int i = 0;i<tt.Length;i++)    
InBlock.gif            
for(int j = 0;j<tt.Length;j++)
InBlock.gif                
for(int k = 0;k<tt.Length;k++)
InBlock.gif                    Console.WriteLine(GetTheDatas()[i]
*GetTheDatas()[j]*GetTheDatas()[k]);
InBlock.gif        Console.ReadLine();
InBlock.gif        Console.WriteLine(inNumber);    
//这里输出多少?
InBlock.gif
        Console.ReadLine();
InBlock.gif        
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private static int[] GetTheDatas()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        inNumber
++;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
return (new int[]dot.gif{1,2,3});    
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
很容易得出输出应该为1+3*3*3*3=82,因为每次循环都会调用3次GetTheData()函数.
那么第一段代码会输出什么那?
因为foreach是在GetTheDatas()返回的Enumerators上的迭代,而不像for循环那样简单地每次调用GetTheDatas()函数,对于每个foreach的每次循环,会隐式地调用GetTheDatas()返回的IEnumerators的GetEnumerator()方法,而不是对GetTheDatas()函数本身进行迭代,所以每次从外层循环进入本层循环都会调用一次GetTheDatas()获取Enumerators,然后在Enumerators上调用GetEnumerator()进行迭代.
这样第一段代码的输出应该为:1+1(第一层循环)+3(第二层循环)+3*3(第三层循环)=14.

转载于:https://www.cnblogs.com/Farseer1215/archive/2005/11/27/285521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值