我对如何最好地实现一个采用整数数组的简单方法并返回最高整数(使用C#2.0)的人有不同意见.
以下是两个实现 - 我有自己的看法哪个更好,为什么,但我会感谢任何公正的意见.
选项A.
public int GetLargestValue(int[] values)
{
try {
Array.Sort(values);
return values[values.Length - 1];
}
catch (Exception){ return -1;}
}
Run Code Online (Sandbox Code Playgroud)
选项B.
public int GetLargestValue(int[] values)
{
if(values == null)
return -1;
if(values.Length < 1)
return -1;
int highestValue = values[0];
foreach(int value in values)
if(value > highestValue)
highestValue = value;
return highestValue;
}
Run Code Online (Sandbox Code Playgroud)