在没有foreach
循环的情况下,是否有更简洁的方法来实现代码重用?
IEnumerable<Stream> GetStreams() {
// nope
// yield return GetStreamsHelper();
// nope
// return GetStreamsHelper();
// yup
foreach (var x in GetStreamsHelper()) {
yield return x;
}
}
IEnumerable<Stream> GetStreamsHelper() {
using (var stream = OpenStream()) {
yield return stream;
}
}
这是我尝试实现的更完整的例子:
class MoreCompleteExample {
IEnumerable<Stream> GetStreams() {
string[] files = new[] { "f1", "f2" };
foreach (var f in files) {
// HERE I WANT TO USE A HELPER METHOD
// NOTHING SEEMS TO WORK EXCEPT A foreach
// PERHAPS THERE IS A LINQ-y WAY TO WRITE THE foreach?
//return GetStreamsHelper(f);
//yield return GetStreamsHelper(f);
foreach (var x in GetStreamsHelper(f)) {
yield return x;
}
}
}
IEnumerable<Stream> GetStreamsHelper(string filename) {
using (var stream = new FileStream(filename, FileMode.Open)) {
Diddle(stream);
yield return stream;
Caress(stream);
}
}
void Diddle(Stream stream) { /* show the stream some love */ }
void Caress(Stream stream) { /* that was nice but i gotsa go */ }
}
答案 0 :(得分:1)
您必须枚举您的收藏品才能使用收益率。如果您不想在方法中迭代集合,可以将代码更改为下一个代码:
IEnumerable<Stream> GetStreams() {
return GetStreamsHelper();
}
然后你将遍历你方法的集合。