返回 null 还是空集合更好? [英] Is it better to return null or empty collection?
问题描述
这是一个普遍的问题(但我使用的是 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屋!