C# 返回 null 还是空集合更好?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1969993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:18:18  来源:igfitidea点击:

Is it better to return null or empty collection?

c#collections

提问by Omu

That's kind of a general question (but I'm using C#), what's the best way (best practice), do you return null or empty collection for a method that has a collection as a return type ?

这是一个普遍的问题(但我使用的是 C#),最好的方法是什么(最佳实践),对于将集合作为返回类型的方法,您是否返回 null 或空集合?

采纳答案by Omu

Empty collection. Always.

空集合。总是。

This sucks:

这很糟糕:

if(myInstance.CollectionProperty != null)
{
  foreach(var item in myInstance.CollectionProperty)
    /* arrgh */
}

It is considered a best practice to NEVER return nullwhen returning a collection or enumerable. ALWAYSreturn an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.

null返回集合或可枚举时永远不要返回被认为是最佳实践。 总是返回一个空的枚举/集合。它可以防止上述废话,并防止您的汽车被同事和班级用户怂恿。

When talking about properties, always set your property once and forget it

在谈论属性时,总是设置你的属性一次然后忘记它

public List<Foo> Foos {public get; private set;}

public Bar() { Foos = new List<Foo>(); }

In .NET 4.6.1, you can condense this quite a lot:

在 .NET 4.6.1 中,你可以浓缩很多:

public List<Foo> Foos { get; } = new List<Foo>();

When talking about methods that return enumerables, you can easily return an empty enumerable instead of null...

在谈论返回可枚举的方法时,您可以轻松地返回一个空的可枚举而不是null...

public IEnumerable<Foo> GetMyFoos()
{
  return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}

Using Enumerable.Empty<T>()can be seen as more efficient than returning, for example, a new empty collection or array.

使用Enumerable.Empty<T>()可以被视为比返回更有效,例如,一个新的空集合或数组。

回答by Karmic Coder

Returning null could be more efficient, as no new object is created. However, it would also often require a nullcheck (or exception handling.)

返回 null 可能更有效,因为没有创建新对象。但是,它通常也需要null检查(或异常处理)。

Semantically, nulland an empty list do not mean the same thing. The differences are subtle and one choice may be better than the other in specific instances.

从语义上讲,null和空列表并不意味着同一件事。差异是微妙的,在特定情况下,一种选择可能比另一种更好。

Regardless of your choice, document it to avoid confusion.

无论您的选择如何,请记录下来以避免混淆。

回答by Bozho

Depends on your contractand your concrete case. Generally it's best to return empty collections, but sometimes (rarely):

取决于你的合同和你的具体情况。通常最好返回空集合,但有时(很少):

  • nullmight mean something more specific;
  • your API (contract) might force you to return null.
  • null可能意味着更具体的东西;
  • 您的 API(合同)可能会迫使您返回null.

Some concrete examples:

一些具体的例子:

  • an UI component (from a library out of your control), might be rendering an empty table if an empty collection is passed, or no table at all, if null is passed.
  • in a Object-to-XML (JSON/whatever), where nullwould mean the element is missing, while an empty collection would render a redundant (and possibly incorrect) <collection />
  • you are using or implementing an API which explicitly states that null should be returned/passed
  • UI 组件(来自不受您控制的库)如果传递空集合,则可能会呈现空表,或者如果传递 null 则根本没有表。
  • 在 Object-to-XML (JSON/whatever) 中,哪里null意味着元素丢失,而空集合将呈现冗余(并且可能不正确)<collection />
  • 您正在使用或实现一个 API,该 API 明确指出应返回/传递 null

回答by dxh

If an empty collection makes sense semantically, that's what I prefer to return. Returning an empty collection for GetMessagesInMyInbox()communicates "you really do not have any messages in your inbox", whereas returning nullmight be useful to communicate that insufficient data is available to say what the list that might be returned ought to look like.

如果一个空集合在语义上有意义,那就是我更喜欢返回的。返回一个空集合表示GetMessagesInMyInbox()“您的收件箱中确实没有任何消息”,而返回null可能有助于传达没有足够的数据来说明可能返回的列表应该是什么样子。

回答by Henric

We had this discussion among the development team at work a week or so ago, and we almost unanimously went for empty collection. One person wanted to return null for the same reason Mike specified above.

大约一周前,我们在工作中的开发团队中进行了此讨论,我们几乎一致同意进行空收集。出于 Mike 上面指定的相同原因,有人想要返回 null。

回答by mothis

Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).

空集合。如果您使用 C#,则假设最大化系统资源不是必需的。虽然效率较低,但返回 Empty Collection 对所涉及的程序员来说要方便得多(原因 Will 已在上面概述)。

回答by RichardOD

From the Framework Design Guidelines 2nd Edition(pg. 256):

来自框架设计指南第 2 版(第 256 页):

DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.

不要从集合属性或从返回集合的方法中返回空值。而是返回一个空集合或一个空数组。

Here's another interesting article on the benefits of not returning nulls (I was trying to find something on Brad Abram's blog, and he linked to the article).

这是另一篇关于不返回空值的好处的有趣文章(我试图在 Brad Abram 的博客上找到一些东西,他链接到了这篇文章)。

Edit-as Eric Lippert has now commented to the original question, I'd also like to link to his excellent article.

编辑-正如埃里克·利珀特 (Eric Lippert) 现在对原始问题的评论,我还想链接到他的优秀文章

回答by Larry Watanabe

Depends on the situation. If it is a special case, then return null. If the function just happens to return an empty collection, then obviously returning that is ok. However, returning an empty collection as a special case because of invalid parameters or other reasons is NOT a good idea, because it is masking a special case condition.

视情况而定。如果是特殊情况,则返回null。如果函数恰好返回一个空集合,那么显然返回是可以的。但是,由于参数无效或其他原因将空集合作为特殊情况返回并不是一个好主意,因为它掩盖了特殊情况。

Actually, in this case I usually prefer to throw an exception to make sure it is REALLY not ignored :)

实际上,在这种情况下,我通常更喜欢抛出异常以确保它真的不会被忽略:)

Saying that it makes the code more robust (by returning an empty collection) as they do not have to handle the null condition is bad, as it is simply masking a problem that should be handled by the calling code.

说它使代码更健壮(通过返回一个空集合),因为它们不必处理 null 条件是不好的,因为它只是掩盖了应该由调用代码处理的问题。

回答by Jason Baker

I would argue that nullisn't the same thing as an empty collection and you should choose which one best represents what you're returning. In most cases nullis nothing (except in SQL). An empty collection is something, albeit an empty something.

我认为这null与空集合不同,您应该选择哪一个最能代表您要返回的内容。在大多数情况下null什么都不是(除了在 SQL 中)。一个空的集合是一些东西,尽管是一个空的东西。

If you have have to choose one or the other, I would say that you should tend towards an empty collection rather than null. But there are times when an empty collection isn't the same thing as a null value.

如果您必须选择其中之一,我会说您应该倾向于空集合而不是空集合。但有时空集合与空值不同。

回答by Jeffrey L Whitledge

There is one other point that hasn't yet been mentioned. Consider the following code:

还有一点还没有提到。考虑以下代码:

    public static IEnumerable<string> GetFavoriteEmoSongs()
    {
        yield break;
    }

The C# Language will return an empty enumerator when calling this method. Therefore, to be consistant with the language design (and, thus, programmer expectations) an empty collection should be returned.

调用此方法时,C# 语言将返回一个空的枚举数。因此,为了与语言设计(以及程序员的期望)保持一致,应该返回一个空集合。