所以我创建了一个简单的代码,它将两个不同的数组传递给一个方法,以检查异常。但是有一个问题 - 当我传递数组时,如果缓存了异常,在我的Exceptions“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");
}
}
}
答案 0 :(得分:1)
您的ValidateArray方法接收一些数据。为方便起见,它命名为#34; array"。其他方法可能引用相同的数据,它们可能有自己的名称。例如,调用IsCommonEnd的方法用于命名该数组" myPreciousArray",IsCommonEnd将其命名为" b"和ValidateArray调用它"数组"。即使有一种方法让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();
}
答案 1 :(得分: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();
}