它是更好地返回null或空集? [英] Is it better to return null or empty collection?

查看:614
本文介绍了它是更好地返回null或空集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎样的一个普遍问题(但我使用C#),什么是最好的方式(最佳实践),你返回null或空的集合,有一个集合作为一个返回类型的方法?

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 ?

推荐答案

空集合。始终。

这很烂:

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

它被认为是最好的做法永远不会返回返回集合或枚举时始终返回一个空枚举/集合。它prevents上述废话,和prevents你的车用的同事和你的类的用户得到怂恿。

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

当谈到性能,总是设置你的财产一次,忘了

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>(); }

在.NET 4.6.1,则您可以将这个颇多:

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

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...

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

使用<一个href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb341042(v=vs.100).aspx\"><$c$c>Enumerable.Empty<T>()可以被看作是不是返回,例如,一个新的空集合或阵列更有效。

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

这篇关于它是更好地返回null或空集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆