这是一个广泛的问题(可是我正在使用C#),最好的方法是什么(最佳实践),对于以集合为返回类型的方法,您是否返回null或空集合? 数组
我想在这里举例说明。 函数
在这里考虑一个案例。 spa
int totalValue = MySession.ListCustomerAccounts() .FindAll(ac => ac.AccountHead.AccountHeadID == accountHead.AccountHeadID) .Sum(account => account.AccountValue);
在这里考虑我正在使用的功能.. code
1. ListCustomerAccounts() // User Defined 2. FindAll() // Pre-defined Library Function
我能够轻松地使用ListCustomerAccount
和FindAll
代替。 对象
int totalValue = 0; List<CustomerAccounts> custAccounts = ListCustomerAccounts(); if(custAccounts !=null ){ List<CustomerAccounts> custAccountsFiltered = custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID == accountHead.AccountHeadID ); if(custAccountsFiltered != null) totalValue = custAccountsFiltered.Sum(account => account.AccountValue).ToString(); }
注意:因为AccountValue不为null
,因此Sum()函数将不会返回null
。,所以我能够直接使用它。 get
空集合。 老是。 it
这很烂: io
if(myInstance.CollectionProperty != null) { foreach(var item in myInstance.CollectionProperty) /* arrgh */ }
最好的作法是在返回集合或可枚举null
时永远不要返回null
。 老是返回一个空的可枚举/集合。 它能够防止上述的废话,并防止您的汽车被班上的同事和用户所困扰。 foreach
在谈论属性时,请始终设置一次属性,而后忘记它 List
public List<Foo> Foos {public get; private set;} public Bar() { Foos = new List<Foo>(); }
在.NET 4.6.1中,您能够将其压缩得不少:
public List<Foo> Foos { get; } = new List<Foo>();
当谈论返回可枚举的方法时,您能够轻松地返回一个空的可枚举而不是null
。
public IEnumerable<Foo> GetMyFoos() { return InnerGetFoos() ?? Enumerable.Empty<Foo>(); }
使用Enumerable.Empty<T>()
能够被认为比返回例如新的空集合或数组更有效。
返回null可能更有效,由于不会建立新对象。 可是,它一般也须要进行null
检查(或异常处理)。
从语义上讲, null
和空列表并不意味着同一件事。 差别是细微的,在特定状况下,一种选择可能会比另外一种更好。
不管您选择哪一种方式,都要记录在案,以避免形成混淆。
取决于您的合同和具体状况 。 一般,最好返回空集合 ,但有时( 不多 ):
null
可能意味着更具体; null
。 一些具体的例子:
null
表示元素丢失,而空集合则表示冗余(可能不正确) <collection />
若是一个空集合在语义上有意义,那就是我但愿返回的内容。 为GetMessagesInMyInbox()
返回空集合将传达“您的收件箱中确实没有任何消息”,而返回null
可能对传达可用数据不足以说明可能返回的列表应该是什么样子颇有用。