编写异常辅助方法

MP1*_*MP1 1 c# syntax exception throw propagation

我是 C# 新手,正在练习抛出异常。从辅助方法抛出异常以缩短所需的代码量是一种好习惯吗?像这样:

    public static void ThrowExcIfNull<T>(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
    }
Run Code Online (Sandbox Code Playgroud)

另外,是否可以编写文档说“从 someMethod 抛出异常”?任何信息都会有所帮助!谢谢

Ayb*_*ybe 5

我认为您应该使用以下模式:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么?

  • 你公开ThrowExcIfNull了一个扩展方法,老实说这很奇怪
  • 如果您查看https://referencesource.microsoft.com/#q=throwif您会发现它们从未公开
  • 除了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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是现在您有另一个问题,堆栈跟踪中显示的第一个方法将是ThrowExcIfNull

在此处输入图片说明

在不使用辅助方法的情况下查看差异:

在此处输入图片说明

错误的来源一目了然。

您可能需要这种方法:

  • 如果你在数百个地方使用它
  • 如果消息要翻译成用户的文化,例如中文
  • 等等

  • 此外,将 `throw` 放入辅助方法有助于内联调用方法。在大量热路径中,这可以提高性能。 (3认同)