如果yield return从未发生,是否返回null?

发布于 2024-09-13 14:09:15 字数 108 浏览 2 评论 0原文

该方法通过yield return 语句返回IEnumerable。

如果yield语句从未出现(它在条件逻辑内部),该方法会返回null,还是会返回一个计数为0的Enumerable?

The method returns IEnumerable via a yield return statement.

If the yield statement never occurs (it's inside conditional logic), will the method return null, or will it return an Enumerable with a count of 0?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

噩梦成真你也成魔 2024-09-20 14:09:15

一个有效的 IEnumerable,当您迭代它时不会产生任何值。

想一想:您可以将 IEnumerable 生成器存储在变量中 - 当您实际迭代结果时,代码本身就会被执行。如果您有 null,您如何执行代码?或者您如何知道该函数在不运行的情况下不会产生任何结果。

A valid IEnumerable that produces no values when you iterate through it.

Just think of it: You can store the IEnumerable generator in a variable - the code itself just gets executed when you actually iterate through the results. How could you execute the code if you had null? Or how did you know the function doesn't yield anything without running it.

一曲琵琶半遮面シ 2024-09-20 14:09:15

后者——无论如何,您都能够GetEnumerator(),只是不会有任何可枚举的项目。这相当于Enumerable.Empty

The latter -- you're going to be able to GetEnumerator() no matter what, there just won't be any items to enumerate. This is equivalent to Enumerable.Empty<T>.

你列表最软的妹 2024-09-20 14:09:15

事实上,倾向于大量使用枚举的 2.0 编码人员在他们的工具包中会有一个标准部分:

public static IEnumerable<T> EmptyEnum<T>()
{
    yield break;
}

Before System.Linq.Enumerable.Empty() come around 。在很多情况下非常有用,通常正是因为它不返回 null。例如,如果 GetIntEnum() 可以返回某种 IEnumerable 类型,但也可以返回 null,那么 GetIntEnum() ?? Enumerable.Empty() 为我们提供了始终可以安全枚举的内容(假设这是空结果情况下所需的行为)。

Indeed, 2.0 coders who leant toward heavy use of enumerations would have a standard piece in their toolkits of:

public static IEnumerable<T> EmptyEnum<T>()
{
    yield break;
}

Before System.Linq.Enumerable.Empty() came along . Very useful in a lot of cases, quite often precisely because it doesn't return null. For example, if GetIntEnum() can return some sort of IEnumerable type but can also return null, then GetIntEnum() ?? Enumerable.Empty<T>() gives us something that is always safe to enumerate over (assuming that's the desired behviour in the case of null results).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文