-1

所以我编写了一个简单的代码,将两个不同的数组传递给一个方法,以检查异常。但是有一个问题——当我传递数组时,如果缓存了一个异常,在我的异常“nameof”部分,它并没有说明哪个数组是那个数组,是什么导致了异常。我需要纠正这一点。那么你有什么想法,我怎么能在我的代码中做到这一点?

public class CommonEnd
{
    public bool IsCommonEnd(int[] a, int[] b)
    {
        ValidateArray(a);
        ValidateArray(b);
        return a.First() == b.First() || a.Last() == b.Last();
    }

    private void ValidateArray(int[] array)
    {
        if (array == null)
        {
            throw new ArgumentNullException(nameof(array), "Array is NULL.");
        }

        if (array.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(array), "Array length can't be smaller that 1");
        }
    }
}
4

2 回答 2

1

您的 ValidateArray 方法接收一些数据。为方便起见,它将该部分命名为“数组”。其他方法可能引用了相同的数据,并且它们可能有自己的名称。例如,调用 IsCommonEnd 的方法曾经将该数组命名为“myPreciousArray”,IsCommonEnd 将其命名为“b”,而 ValidateArray 将其命名为“array”。即使有一种方法可以让 ValidateArray 访问数组的所有其他名称,您应该选择哪一个?

如果需要区分实例,为什么不在实例明显可识别的地方处理呢?就像在您的 IsCommonEnd 方法中一样?像这样的东西:

public bool IsCommonEnd(int[] a, int[] b)
{
    try
    {
    ValidateArray(a);
    }
    catch(ArgumentNullException ex)
    {
        // you know your 'a' array is null, do whatever you want to do about that
        throw; // if you need this exception to propagate, of course

    }
    catch(ArgumentOutOfRangeException ex)
    {
        // you know your 'a' array is too small, do whatever you want to do about that
        throw; // if you need this exception to propagate, of course

    }
    // the same about 'b'
    try
    {
    ValidateArray(b);
    }
    catch(ArgumentNullException ex)
    {
        // you know your 'b' array is null, do whatever you want to do about that
        throw; // if you need this exception to propagate, of course

    }
    catch(ArgumentOutOfRangeException ex)
    {
        // you know your 'b' array is too small, do whatever you want to do about that
        throw; // if you need this exception to propagate, of course

    }
    return a.First() == b.First() || a.Last() == b.Last();
}
于 2018-02-12T14:42:01.377 回答
1

nameof(array)将始终只返回字符串array。为了知道是否a出错b,您可以传递另一个参数并使用nameof更高级别

private void ValidateArray(string which, int[] array)
{
    if (array == null)
    {
        throw new ArgumentNullException(nameof(array), $"Array {which} is NULL.");
    }

    if (array.Length == 0)
    {
        throw new ArgumentOutOfRangeException(nameof(array), $"Array {which} length can't be smaller that 1");
    }
}

在调用方法中:

public bool IsCommonEnd(int[] a, int[] b)
{
    ValidateArray(nameof(a), a);
    ValidateArray(nameof(b), b);
    return a.First() == b.First() || a.Last() == b.Last();
}
于 2018-02-12T14:42:55.007 回答