我是C#的新手,正在练习抛出异常。从助手方法中抛出异常以缩短所需的代码量是一种好习惯吗?像这样:
public static void ThrowExcIfNull<T>(this T[] array)
{
if (array == null) throw new ArgumentNullException("Array is null");
}
/// <summary>
/// Does Something
/// </summary>
/// <param name="x">The int array to be used</param>
/// <exception cref="ArgumentNullException">Thrown when the string is
/// null</exception> //Is this correct?
/// <returns>Some integer</returns>
public static int SomeMethod(this int[] x)
{
ThrowExcIfNull(x);
//Some code here
}
另外,编写文档说“从someMethod抛出异常”是否可以?任何信息都会有帮助!谢谢
我认为你应该使用以下模式:
using System;
public static class MyExtensions
{
/// <summary>
/// Magic method.
/// </summary>
/// <param name="source">
/// The source array.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <c>null</c>.
/// </exception>
/// <returns>
/// Some magic value only you know about.
/// </returns>
public static int SomeMethod(this int[] source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return 42;
}
}
为什么?
ThrowExcIfNull
暴露为扩展方法,说实话这很奇怪CancellationToken.ThrowIfCancellationRequested
,但这是一个特例如果你绝对想要这样的方法
至少传递参数名称,以便更容易调试:
using System;
public static class MyExtensions
{
public static int SomeMethod(this int[] source)
{
ThrowIfNull(source, nameof(source));
return 42;
}
private static void ThrowIfNull(object value, string parameter)
{
if (value == null)
throw new ArgumentNullException(parameter);
}
}
但是现在你有另一个问题,堆栈跟踪中显示的第一个方法是ThrowExcIfNull
:
只需在不使用该辅助方法的情况下查看差异:
错误来自何处。
你可能会想要这个方法: