C# 2.0 的 迭代器 break的问题。

刚了C# 2.0 的迭代器感觉不错,简洁明了。
在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return expression;
yield break;

在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。
// yield-example.cs
using System;
using System.Collections;
public class List
{
    
public static IEnumerable Power(int number, int exponent)
    {
        
int counter = 0;
        
int result = 1;
        
while (counter++ < exponent)
        {
            result 
= result * number;
            yield 
return result;
        }
    }

    
static void Main()
    {
        
// Display powers of 2 up to the exponent 8:
        foreach (int i in Power(28))
        {
            Console.Write(
"{0} ", i);
        }
    }
}
 
输出
2 4 8 16 32 64 128 256


这时,我就产生了一个问题, yield break; 是在迭代器中发出迭代结束信号用的。可是,如果是在迭代器的使用的时候外层break了,迭代器怎么能得到“信号”呢??能否??因为,迭代器如果被中断,迭代器内部要作一些处理,比如:关闭个连接什么的, 如下代码所示:
// yield-break-example.cs
using System;
using System.Collections;
public class List
{
    
public static IEnumerable Power(int number, int exponent)
    {
        
int counter = 0;
        connection.Open();
        
int result = 1;
        
while (counter++ < exponent)
        {
            result 
= result * number;
            yield 
return result;
        }
        connection.Close();
    }

    
static void Main()
    {
        
// Display powers of 2 up to the exponent 8:
        foreach (int i in Power(28))
        {
            Console.Write(
"{0} ", i);
            
if(i > 8break;
        }
    }
}
 

我的connection怎么才能正常Close呢???


原文地址:https://www.cnblogs.com/zhongzf/p/415775.html