//yield return用于无缝实现迭代模式。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class YieldReturn
{
//yield return用于无缝实现迭代模式。
string[] strArr;
public YieldReturn(params string[] arr)
{
strArr = new string[arr.Length];
arr.CopyTo(strArr, 0);
}
//-------一个枚举对象可以对应多个枚举
/// <summary>
/// 反序输出
/// </summary>
public IEnumerable<string> Reverse
{
get
{
for (int i = strArr.Length - 1; i >= 0; i--)
yield return strArr[i];
}
}
/// <summary>
/// 顺序输出
/// </summary>
public IEnumerable<string> PosEven
{
get
{
for (int i=0;i<strArr.Length; i++)
yield return strArr[i];
}
}
public IEnumerable<string> Concat
{
get
{
foreach (string s in Reverse)
yield return s;
foreach (string s in PosEven)
yield return s;
}
}
}
实现:
public static void yieldreturn()
{
YieldReturn yr = new YieldReturn("aaa", "bbb", "ccc");
Console.WriteLine("-----Reverse:");
foreach (string s in yr.Reverse)
Console .WriteLine (s);
Console.WriteLine("-----PosEven:");
foreach (string s in yr.PosEven)
Console.WriteLine(s);
Console.WriteLine("-----Concat:");
foreach (string s in yr.Concat)
Console.WriteLine(s);
}
{
//yield return用于无缝实现迭代模式。
string[] strArr;
public YieldReturn(params string[] arr)
{
strArr = new string[arr.Length];
arr.CopyTo(strArr, 0);
}
//-------一个枚举对象可以对应多个枚举
/// <summary>
/// 反序输出
/// </summary>
public IEnumerable<string> Reverse
{
get
{
for (int i = strArr.Length - 1; i >= 0; i--)
yield return strArr[i];
}
}
/// <summary>
/// 顺序输出
/// </summary>
public IEnumerable<string> PosEven
{
get
{
for (int i=0;i<strArr.Length; i++)
yield return strArr[i];
}
}
public IEnumerable<string> Concat
{
get
{
foreach (string s in Reverse)
yield return s;
foreach (string s in PosEven)
yield return s;
}
}
}
实现:
public static void yieldreturn()
{
YieldReturn yr = new YieldReturn("aaa", "bbb", "ccc");
Console.WriteLine("-----Reverse:");
foreach (string s in yr.Reverse)
Console .WriteLine (s);
Console.WriteLine("-----PosEven:");
foreach (string s in yr.PosEven)
Console.WriteLine(s);
Console.WriteLine("-----Concat:");
foreach (string s in yr.Concat)
Console.WriteLine(s);
}