c# - 函数应该返回什么?

标签 c#

假设我有这样一个函数:

public List<int> func()
{}

现在,出于某种原因我没有任何东西可以放入列表中,所以我将只返回“空的东西”。 根据一个好的做法,我应该在上面的函数中返回以下三个中的哪一个?

return null;
return new List<int>();  
return default(List<int>);  //Is this the same thing as the one above?

最佳答案

返回一个空列表:

return new List<int>();

default(List<int>)将返回 null ;不是空列表!

返回空列表可防止在每次调用您的函数后进行过多的空值检查。参见 Is it better to return null or empty collection?

关于c# - 函数应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226833/

相关文章:

c# - Microsoft.NETCore.UniversalWindowsPlatform 引用的用途是什么?

c# - 如何使用 sharpmap 在地球上渲染一个国家的图像

c# - 自排序列表框

c# - 编译 LESS,压缩 CSS 和 JS 并输出到构建目录

c# - 如何判断XmlTextReader已经读取了多少数据?

c# - 文本框可见属性

c# - 大量数据的插入性能缓慢 (SQL Server/C#)

c# - 错误 MSB4019 : The imported project "C:\Program Files\dotnet\sdk\1.0.3\Microsoft\Portable\v5.0\Microsoft.Portable.CSharp.targets" was not found

c# - 如何在 visual studio mac 中添加对程序集的引用?

c# - Winform窗体关闭事件