在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)时引发的异常
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |