假设我有这样一个函数:
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/