无法使用产量返回打印到控制台
在下面的测试中,当使用yield return时,我无法让Console.WriteLine真正打印。 我正在尝试收益率回报,我知道我对它的理解中缺少一些东西,但无法找出它是什么。为什么 PrintAllYield
中没有打印字符串?
代码:
class Misc1 {
public IEnumerable<string> PrintAllYield(IEnumerable<string> list) {
foreach(string s in list) {
Console.WriteLine(s); // doesn't print
yield return s;
}
}
public void PrintAll(IEnumerable<string> list) {
foreach(string s in list) {
Console.WriteLine(s); // surely prints OK
}
}
}
测试:
[TestFixture]
class MiscTests {
[Test]
public void YieldTest() {
string[] list = new[] { "foo", "bar" };
Misc1 test = new Misc1();
Console.WriteLine("Start PrintAllYield");
test.PrintAllYield(list);
Console.WriteLine("End PrintAllYield");
Console.WriteLine();
Console.WriteLine("Start PrintAll");
test.PrintAll(list);
Console.WriteLine("End PrintAll");
}
}
输出:
Start PrintAllYield
End PrintAllYield
Start PrintAll
foo
bar
End PrintAll
1 passed, 0 failed, 0 skipped, took 0,39 seconds (NUnit 2.5.5).
In the tests below, I cannot get Console.WriteLine to really print when using yield return.
I'm experimenting with yield return and I understand I have something missing in my understanding of it, but cannot find out what it is. Why aren't the strings printed inside PrintAllYield
?
Code:
class Misc1 {
public IEnumerable<string> PrintAllYield(IEnumerable<string> list) {
foreach(string s in list) {
Console.WriteLine(s); // doesn't print
yield return s;
}
}
public void PrintAll(IEnumerable<string> list) {
foreach(string s in list) {
Console.WriteLine(s); // surely prints OK
}
}
}
Test:
[TestFixture]
class MiscTests {
[Test]
public void YieldTest() {
string[] list = new[] { "foo", "bar" };
Misc1 test = new Misc1();
Console.WriteLine("Start PrintAllYield");
test.PrintAllYield(list);
Console.WriteLine("End PrintAllYield");
Console.WriteLine();
Console.WriteLine("Start PrintAll");
test.PrintAll(list);
Console.WriteLine("End PrintAll");
}
}
Output:
Start PrintAllYield
End PrintAllYield
Start PrintAll
foo
bar
End PrintAll
1 passed, 0 failed, 0 skipped, took 0,39 seconds (NUnit 2.5.5).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须实际枚举返回的 IEnumerable 才能看到输出:
当您使用 yield return 关键字时,编译器将为您构造一个状态机。它的代码仅在您实际使用它来迭代返回的枚举时才会运行。
您尝试使用
yield return
打印出string
序列是否有特殊原因?这并不是该功能的真正目的,它是为了简化序列生成器的创建,而不是枚举已生成的序列。foreach
是后者的首选方法。You have to actually enumerate the returned
IEnumerable
to see the output:When you use the
yield return
keyword, the compiler will construct a state machine for you. Its code will only be run when you actually use it to iterate the returned enumerable.Is there a particular reason you're trying to use
yield return
to print out a sequence ofstring
s? That's not really the purpose of the feature, which is to simplify the creation of sequence generators, rather than the enumeration of an already generated sequence.foreach
is the preferred method for the latter.