在C#中,有没有一种方法可以找到最多3个数字? [英] In c# is there a method to find the max of 3 numbers?

查看:89
本文介绍了在C#中,有没有一种方法可以找到最多3个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像Math.Max一样,但是需要3个或多个int参数?

Like Math.Max but takes 3 or params of int?

谢谢

推荐答案

好吧,您可以调用它两次:

Well, you can just call it twice:

int max3 = Math.Max(x, Math.Max(y, z));

如果您发现自己经常这样做,则可以随时编写自己的帮助方法...会很高兴看到我的代码库一次,但不是经常看到。

If you find yourself doing this a lot, you could always write your own helper method... I would be happy enough seeing this in my code base once, but not regularly.

(请注意,这可能比安德鲁的效率更高基于LINQ的答案-但显然您拥有的元素越多,LINQ方法就越具有吸引力。)

(Note that this is likely to be more efficient than Andrew's LINQ-based answer - but obviously the more elements you have the more appealing the LINQ approach is.)

编辑:两全其美的方法可能是自定义方法集的一种方式:

A "best of both worlds" approach might be to have a custom set of methods either way:

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)以获得美观​​且一致的代码。

That way you can write MoreMath.Max(1, 2, 3) or MoreMath.Max(1, 2, 3, 4) without the overhead of array creation, but still write MoreMath.Max(1, 2, 3, 4, 5, 6) for nice readable and consistent code when you don't mind the overhead.

我个人发现它比LINQ方法的 explicit 数组创建更具可读性。

I personally find that more readable than the explicit array creation of the LINQ approach.

这篇关于在C#中,有没有一种方法可以找到最多3个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆