如何记录C#中引用类型的"不可空性"?

Dim*_* C. 6 c#

在C#中,引用类型的实例作为可空指针传递给函数.考虑例如:

public void f(Class classInstanceRef)
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,该函数将期望一个非空指针(在我的经验中占所有情况的95%).记录此函数需要非空指针这一事实的最佳方法是什么?

更新:非常感谢您的回复!

Joh*_*lla 19

在.NET 4中,您将能够使用代码契约,这仅适用于此类事情:

Contract.Requires(classInstanceRef != null);
Run Code Online (Sandbox Code Playgroud)

与此同时,我认为适当的文件和投掷ArgumentNullException是可以接受的.


Rub*_*ins 17

1)确保方法拒绝任何null

if (instanceRef == null)
{
   throw new ArgumentNullException("instanceRef");
}
Run Code Online (Sandbox Code Playgroud)

2)添加

/// <exception cref="T:System.ArgumentNullException"> is thrown 
/// when <paramref name="instanceRef"/> is <c>null</c></exception>
Run Code Online (Sandbox Code Playgroud)

将null引用(在Visual Basic中为Nothing)传递给不接受它作为有效参数的方法(MSDN)时引发的异常

  • 而不是`ArgumentException`你应该使用`ArgumentNullException`. (4认同)
  • ArgumentNullException构造函数的这个重载采用参数的名称,而不是异常消息,所以它应该是新的ArgumentException("Class"); (2认同)