像Math.Max一样,但需要3或int参数?
谢谢
Answers:
好吧,您可以调用它两次:
int max3 = Math.Max(x, Math.Max(y, z));
如果您发现自己在做很多事情,则可以总是编写自己的帮助程序方法...我很高兴在我的代码库中看到过一次,但并不定期。
(请注意,这可能比安德鲁基于LINQ的答案更有效-但显然,您拥有的元素越多,LINQ方法就越具有吸引力。)
编辑:“两全其美”的方法可能是采用以下两种方法之一来定制一组方法:
public static class MoreMath
{
// This method only exists for consistency, so you can *always* call
// MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
// depending on your argument count.
public static int Max(int x, int y)
{
return Math.Max(x, y);
}
public static int Max(int x, int y, int z)
{
// Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
// Time it before micro-optimizing though!
return Math.Max(x, Math.Max(y, z));
}
public static int Max(int w, int x, int y, int z)
{
return Math.Max(w, Math.Max(x, Math.Max(y, z)));
}
public static int Max(params int[] values)
{
return Enumerable.Max(values);
}
}
这样,您可以编写MoreMath.Max(1, 2, 3)或MoreMath.Max(1, 2, 3, 4)不编写数组创建的开销,但是MoreMath.Max(1, 2, 3, 4, 5, 6)当您不介意开销时,仍然可以编写出易于阅读且一致的代码。
我个人发现,这比LINQ方法的显式数组创建更具可读性。
MoreMath.Max(x, y, z)比LINQ方法IMO更易读。
public static int Max(params int[] values) 呢?
Max(1, 2, 3)将无缘无故创建一个数组。通过为相对少量的参数提供一些重载,可以提高效率,而不会影响调用方的可读性。
您可以使用Enumerable.Max:
new [] { 1, 2, 3 }.Max();
[]。好漂亮
new int[] { 1,2,3 }。因此,它是一个类型为int的数组,该数组由其内容隐式确定。
Linq具有Max函数。
如果您有一个IEnumerable<int>,可以直接调用它,但是如果您需要在单独的参数中使用它们,则可以创建如下函数:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
然后您可以这样称呼它:max(1, 6, 2),它允许任意数量的参数。
Max而不是max,并使它成为静态的:)通过为更少的参数重载它,您也可以使它更有效。
如果由于某种原因(例如,Space Engineers API),System.array没有为Max定义,也没有访问Enumerable的权限,则解决最大n个值的方法是:
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
此函数采用整数数组。(我完全理解@Jon Skeet对发送数组的抱怨。)
这可能有点矫kill过正。
public static int GetMax(int[] array) // must be a array of ints
{
int current_greatest_value = array[0]; // initializes it
for (int i = 1; i <= array.Length; i++)
{
// compare current number against next number
if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
{
// array[i+1] exists
if (array[i] < array[i+1] || array[i] <= current_greatest_value)
{
// current val is less than next, and less than the current greatest val, so go to next iteration
continue;
}
} else
{
// array[i+1] doesn't exist, we are at the last element
if (array[i] > current_greatest_value)
{
// current iteration val is greater than current_greatest_value
current_greatest_value = array[i];
}
break; // next for loop i index will be invalid
}
// if it gets here, current val is greater than next, so for now assign that value to greatest_value
current_greatest_value = array[i];
}
return current_greatest_value;
}
然后调用函数:
int highest_val = GetMax (new[] { 1,6,2,72727275,2323});
// highest_val = 72727275