gpt4 book ai didi

c# - 使用 yield return 的语法问题 IEnumerable 方法

转载 作者:太空狗 更新时间:2023-10-29 21:10:12 25 4
gpt4 key购买 nike

这是我的方法:

static IEnumerable<DateTime> GetMonths(DateTime from, DateTime to)
{
// if logs is not uptodate
TimeSpan logsMissingTimespan = to - from;

if (logsMissingTimespan != new TimeSpan(0))
{
return GetMonthsBetweenTwoDates(from, to);
}

return null; // Why this line ?
}

private static IEnumerable<DateTime> GetMonthsBetweenTwoDates(DateTime from, DateTime to)
{

DateTime date = from;
DateTime lastDate = DateTime.MaxValue;

while (date < to)
{
if (lastDate.Month != date.Month)
{
lastDate = date;
yield return lastDate;
}
date = date.AddDays(1);
}
}

它工作正常,但我想我可以像这样写一些更干净的东西:

static IEnumerable<DateTime> GetMonths(DateTime from, DateTime to)
{
TimeSpan logsMissingTimespan = to - from;

if (logsMissingTimespan == new TimeSpan(0))
{
yield break;
}

return GetMonthsBetweenTwoDates(from, to);
}

但是我有一个错误信息:

Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.

为什么我应该有一个return null,正确的语法是什么?

编辑:

所以,正确的方法是使用 Enumerable.Empty :

static IEnumerable<DateTime> GetMonths(DateTime from, DateTime to)
{
// if logs is not uptodate
TimeSpan logsMissingTimespan = to - from;

if (logsMissingTimespan != new TimeSpan(0))
{
return GetMonthsBetweenTwoDates(from, to);
}

return Enumerable.Empty<DateTime>();
}

最佳答案

因为你用了yield这个词它现在期望该方法一次产生一个元素。它只能使用 yeild returnyield break每次迭代返回一个元素。

你应该使用 Enumerable.Empty<DateTime>();而不是 yield break .

关于c# - 使用 yield return 的语法问题 IEnumerable<T> 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8311340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com