是否最好返回null或空集合? [英] Is it better to return null or empty collection?

查看:160
本文介绍了是否最好返回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 */
}

当返回一个集合或枚举时,不要返回 null 始终返回空的枚举/集合。

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

当谈到返回枚举的方法时,可以很容易地返回一个空的枚举而不是 null ...

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

使用 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天全站免登陆