這是一個廣泛的問題(可是我正在使用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
可能對傳達可用數據不足以說明可能返回的列表應該是什麼樣子頗有用。