Yield in foreach or GetEnumerator()?
本文关键字:GetEnumerator or in foreach Yield | 更新日期: 2023-09-27 17:54:03
在这种情况下更可取:
IEnumerator<Cat> EnumerateCats()
{
var rawCats = GetRawCats();
foreach(var cat in rawCats)
{
var typedCat = new Cat
{
Name = cat.Key;
Breed = cat.Value;
};
yield return typedCat;
}
}
或
IEnumerator<Cat> EnumerateCats()
{
return GetRawCats()
.Select(cat => new Cat
{
Name = cat.Key;
Breed = cat.Value;
})
.GetEnumerator();
}
我更喜欢最后一个代码示例。它的工作方式与第一个相同吗?
我不确定为什么你需要返回一个IEnumerator<Cat>
. 我会简单地更改它以返回一个IEnumerable<Cat>
,所以你可以简单地写:
IEnumerable<Cat> EnumerateCats()
=> GetRawCats()
.Select(cat => new Cat
{
Name = cat.Key;
Breed = cat.Value;
});
在这个
例子中,您可以看到使用 yield
编写方法和不使用
static void Main(string[] args)
{
foreach (int i in List())
{
Console.WriteLine($"In List foreach {i}");
}
Console.WriteLine("*****");
foreach (int i in Yield())
{
Console.WriteLine($"In Yeild foreach {i}");
}
}
private static IEnumerable<int> List()
{
var inputList = new List <int> { 1, 2, 3 };
List<int> outputlist = new List<int>();
foreach (var i in inputList)
{
Console.WriteLine($"In List Method {i}");
outputlist.Add(i);
}
return outputlist.AsEnumerable();
}
private static IEnumerable<int> Yield()
{
var inputList = new List<int> { 1, 2, 3 };
foreach (var i in inputList)
{
Console.WriteLine($"In Yield Method {i}");
yield return i;
}
}
这是输出:
In List Method 1
In List Method 2
In List Method 3
In List foreach 1
In List foreach 2
In List foreach 3
*****
In Yield Method 1
In Yield foreach 1
In Yield Method 2
In Yield foreach 3
In Yield Method 3
In Yield foreach 3
通过使用 yield 语句,您可以减少内存使用量,因为每次到达 yield 语句时,调用都会返回。另一种方式是在返回到调用方之前构建孔集合。