迭代器实现时候程序无法继续执行怎么回事?

gudicao 2012-03-01 07:29:59

static void Main(string[] args)
{
string Tem_str = "";
string str = "abcdefg"; //对str字符串逆序输出
foreach (object i in Transpose(str))
{
Tem_str += i.ToString();

}
Console.WriteLine(Tem_str);

Console.ReadKey();
}


public static IEnumerable<object> Transpose(string n)
{

for (int i = n.Length - 1; i >= 0; i++)
{
yield return (object)n[i];
}

}







...全文
72 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2012-03-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 caozhy 的回复:]
C# 3 可能需要这么写:

public static IEnumerable<object> Transpose(string n)
{
return n.Reverse().Select(x => (object)x);
}
[/Quote]
比如这个代码,用yield return这么写:
public static IEnumerable<object> Transpose(string n)
{
foreach (var item in n.Reverse().Select(x => (object)x))
yield return item;
}
蔡袅 2012-03-01
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 gudicao 的回复:]

请问yield return 和return有什么区别呢?
[/Quote]在迭代器块中用于向枚举数对象提供值

// 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(2, 8))
{
Console.Write("{0} ", i);
}
}
}

//输出:2 4 8 16 32 64 128 256


gudicao 2012-03-01
  • 打赏
  • 举报
回复
请问yield return 和return有什么区别呢?
threenewbee 2012-03-01
  • 打赏
  • 举报
回复
C# 3 可能需要这么写:

public static IEnumerable<object> Transpose(string n)
{
return n.Reverse().Select(x => (object)x);
}
threenewbee 2012-03-01
  • 打赏
  • 举报
回复
public static IEnumerable<object> Transpose(string n)
{
return n.Reverse();
}
gudicao 2012-03-01
  • 打赏
  • 举报
回复
哦,居然犯这等错误啊,那么yield return 和return有什么区别呢?
蔡袅 2012-03-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zzzzv0 的回复:]

i++改成i--
[/Quote]没错,这个迭代会没有结束
zzzzv0 2012-03-01
  • 打赏
  • 举报
回复
i++改成i--

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧