首先,作为一种良好做法,我建议习惯于在每个算法开始时进行一些错误情况检查,以确保完全覆盖您的输入。
其次,正如 Eric Lippert 所说,您必须为变量分配有意义的名称,并避免在用途不同时重复使用它们,除非您过度使用优化一些经常在循环中运行的算法,并进行大量迭代。
您还可以利用输出变量的强大功能:必须在函数返回之前设置它们。在异常情况下,该函数没有义务为输出变量设置任何值。所以你会有一个很好的函数,它从arrayA返回minIndex和minValue。
如果您需要一个永不抛出异常的“稳定”函数,我已经编写了另一个实现“bool TryDoSomenthing(out result)”模式的版本。此函数仅在索引计算成功的情况下返回“true”。我在异常不理想的系统上广泛使用这种模式,因为在多个顺序失败的情况下它们会影响性能。
代码:
// Finds the index of the lowest value in the array, considering just the 'n' first numbers.
// Throws exceptions in case of bad input parameters.
private static void GetMin(double[] a, int n, out int minIndex, out double minValue)
{
if (a == null)
throw new ArgumentNullException(nameof(a));
if (a.Length <= 0)
throw new ArgumentException("array 'a' contains no elements");
if (n <= 0)
return new ArgumentException("'n' must be greater than 0");
minIndex = 0;
minValue = a[0];
if (n > a.Length)
n = a.Length;
for (i = 1; i < n; ++i)
if (minValue > a[i])
minValue = a[(minIndex = i)];
}
// Finds the index of the lowest value in the array, considering just the 'n' first numbers.
// Returns 'false' in case of bad input parameters.
private static bool TryGetMin(double[] a, int n, out int minIndex, out double minValue)
{
if (a == null || a.Length <= 0 || n <= 0)
{
minIndex = -1;
minValue = double.MinValue;
return false;
}
minIndex = 0;
minValue = a[0];
if (n > a.Length)
n = a.Length;
for (i = 1; i < n; ++i)
if (minValue > a[i])
minValue = a[(minIndex = i)];
return true;
}
internal static void Main()
{
double[] arrayA = new double[] { 3.0, 2.0, 4.0, 1.0 };
object[] arrayB = new object[] { 'x', 'y', 'z', 'w' };
int minIndex; // index of minimum value found in 'arrayA'
double minValue; // minimum value found in 'arrayA'
object b; // used for storing the element of arrayB at 'minIndex'
// With GetMin() - this code will throw an exception on bad inputs:
GetMin(arrayA, 3, out minIndex, out minValue);
b = arrayB[minIndex];
// Or with TryGetMin:
if(TryGetMin(arrayA, 3, out minIndex, out minValue))
{
b = arrayB[minIndex];
}
else
{
// TryGetMin() was not successful, do something about it.
b = null;
}
// Or simply:
b = TryGetMin(arrayA, 3, out minIndex, out minValue) ? arrayB[minIndex] : null;
//...
}