我从三个变量中得到三个值.如何查看谁是最高号码谁是最低号码?
数字表示如下:
private int _score1;
private int _score2;
private int _score2;
Run Code Online (Sandbox Code Playgroud)
码:
Public int Highest
{
return the highest number here;
}
public int Lowest
{
return the lowest number here;
}
Run Code Online (Sandbox Code Playgroud)
我可以计算构造函数中的最高和最低数字吗?
强制性的Linq回答:
Public int Highest(params int[] inputs)
{
return inputs.Max();
}
public int Lowest(params int[] inputs)
{
return inputs.Min();
}
Run Code Online (Sandbox Code Playgroud)
这个的美妙之处在于它可以采用任意数量的整数输入.为了使其成为故障安全,您应该检查null/empty输入数组(意味着没有任何内容传递给方法).
要在没有Linq的情况下执行此操作,您基本上只需要模仿扩展方法执行的逻辑:
Public int Lowest(params int[] inputs)
{
int lowest = inputs[0];
foreach(var input in inputs)
if(input < lowest) lowest = input;
return lowest;
}
Run Code Online (Sandbox Code Playgroud)
再次,为了使其万无一失,您应检查空或空输入数组,因为调用Lowest()将抛出ArrayIndexOutOfBoundsException.
这是一种方法:
public int Highest
{
get { return Math.Max(_score1, Math.Max(_score2, _score3)); }
}
public int Lowest
{
get { return Math.Min(_score1, Math.Min(_score2, _score3)); }
}
Run Code Online (Sandbox Code Playgroud)
int[] numbers = new[] { _score1, _score2, _score3 };
int min = numbers.Min();
int max = numbers.Max();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49605 次 |
| 最近记录: |