2009-08-24 20 views
6

在C#中,引用類型的實例作爲可空指針傳遞給函數。考慮到例如:如何記錄C#中引用類型的「不可空」性?

public void f(Class classInstanceRef) 

在大多數情況下,該功能將期待一個非空指針(在我的經驗,所有病例的95%)。記錄這個函數需要一個非空指針的最好方法是什麼?

更新:非常感謝您的回覆至今!

回答

17

1)確認方法拒絕任何空

if (instanceRef == null) 
{ 
    throw new ArgumentNullException("instanceRef"); 
} 

2)添加

/// <exception cref="T:System.ArgumentNullException"> is thrown 
/// when <paramref name="instanceRef"/> is <c>null</c></exception> 

時在Visual Basic中 空引用(沒有)是引發的異常傳遞給方法,它不會接受它作爲有效參數(MSDN)

+4

您應該使用'ArgumentNullException'來代替'ArgumentException'。 – 2009-08-24 14:16:30

+1

你不想使用'ArgumentNullException'嗎? – LukeH 2009-08-24 14:16:34

+1

拋出ArgumentNullException而不是ArgumentException不是最好嗎? – 2009-08-24 14:16:41

3
Debug.Assert(classInstanceRef != null); 
+1

這就是現在我稱之爲文件......你是否經常檢查你的程序的調試輸出? – 2009-08-24 14:25:01

+1

如果您在調試模式下編譯,則會在運行時彈出一個斷言失敗對話框。你需要多少錢? – 2009-08-24 14:44:34

19

在.NET 4中,你將不得不使用code contracts,這意味着只是這樣的事情的能力:

Contract.Requires(classInstanceRef != null); 

在此期間,我認爲適當的文件和拋ArgumentNullException是可以接受的。

-1
if(classInstanceRef == null) { throw new NullReferenceException("classInstanceRef"); } 

///<remarks>classInstanceRef cannot be null</remarks> 
+2

您不應該拋出NulLReferenceException(按照指導http://msdn.microsoft.com/en-us/library/ms229007.aspx)。優先使用ArgumentNullException。 – 2009-08-24 14:31:03

+0

的確,懶惰的代表我在那裏......不會在我自己的代碼中做到這一點。 – Massif 2009-08-24 15:08:52

2

我會做這樣的事情:

/// <summary> 
/// Does stuff 
/// </summary> 
/// <param name="classInstanceRef">some documentation</param> 
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="classInstanceRef"/> is null.</exception> 
public void f(Class classInstanceRef) 
{ 
    if (classInstanceRef == null) 
    throw new ArgumentNullException("classInstanceRef"); 
}