2012-07-19 73 views
2

我想知道哪些方法從.NET Framework返回null。簡單的方法來知道哪些方法在.NET Framework中返回null

例如;當我從IQueryable調用搜索方法時,如果搜索未找到任何結果,它將返回null或空集合。

我們學習了一些方法,但是當涉及新方法時,我總是編寫額外的代碼行,這使得代碼難以閱讀。

有沒有簡單的方法來解決這個問題?

編輯:

我怎麼總是遇到這樣的問題是這樣的:

List<int> ints = new List<int>(); // Suppose this is a list full of data 

// I wanna make sure that FindAll does not return null 
// So getting .Count does not throw null reference exception 
int numOfPositiveInts = ints.FindAll(i => i > 0).Count; 

// This is not practical, but ensures against null reference return 
int numOfPositiveInts = ints.FindAll(i => i > 0) != null ? ints.FindAll(i => i > 0).Count : 0; 

第一種選擇是可行的,但是並不安全,而第二個選項防止任何空引用異常,但降低了可讀性。

謝謝。

+0

如果方法返回ValueType類型,它不能爲null,如果它的referenceType它可以爲null或者我誤解了你的問題。 – Leri 2012-07-19 12:52:03

+0

大多數方法在它們返回null時在描述中指定。例如,'Where'永遠不會返回null。如果Count()== 1,SingleOrDefault將返回單個元素,如果沒有元素,默認值(如果引用值爲null,則爲0或false),如果存在多個元素,則拋出異常。 – 2012-07-19 12:52:58

+0

@PLB,如果方法返回類型是引用類型,它總是可以返回null嗎?我認爲一些返回引用的方法(尤其是Collection類型)會返回空集合而不是空引用。 – 2012-07-19 13:00:41

回答

1

當您安裝Code Contracts時,會安裝輔助程序集,爲您提供大部分核心庫的合同。有一個編輯器插件以IntelliSense風格顯示它們。