如何在C#中记录引用类型的“非空性”?

6
在C#中,引用类型的实例作为可空指针传递给函数。例如,请考虑以下代码:
public void f(Class classInstanceRef)

在大多数情况下,该函数将期望一个非空指针(在我的经验中95%的情况下)。如何最好地记录该函数期望一个非空指针的事实?

更新:非常感谢迄今为止您的回复!

6个回答

18

在.NET 4中,你将能够使用代码合同,这些合同就是为了处理这种情况而设计的:

Contract.Requires(classInstanceRef != null);

同时,我认为适当的文档说明和抛出ArgumentNullException是可以接受的。


16

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中的Nothing)传递给不接受其作为有效参数的方法时,会引发异常。 (MSDN)

4
应使用ArgumentNullException而非ArgumentException - Martin Liversage
1
你不想使用 ArgumentNullException 吗? - LukeH
1
抛出ArgumentNullException而不是ArgumentException会更好吧? - Randy Levy
2
这个ArgumentNullException构造函数的重载需要参数的名称,而不是异常消息,因此应该使用new ArgumentException("Class")。 - Thomas Levesque

4

请查看代码合同库: http://research.microsoft.com/en-us/projects/contracts/

它使您能够指定代码的前提条件,并使用代码库的静态分析进行验证:

Contract.Requires( x ! = null );

这个库将被包含在.NET Framework v4中,而之前版本的框架需要商业许可证。


3
Debug.Assert(classInstanceRef != null);

1
这不是我所谓的文档... 你有多经常检查程序的调试输出? - Thomas Levesque
1
如果你在调试模式下编译,它会在运行时弹出一个断言失败对话框。你还希望更直接一些吗? - Ed Guiness

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");
}

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

?

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

2
根据指南 http://msdn.microsoft.com/en-us/library/ms229007.aspx ,不应抛出NulLReferenceException。最好使用ArgumentNullException。 - Randy Levy
确实,那是我懒惰的想法...在我的代码中不会这样做。 - Massif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接