简体   繁体   English

枚举值的最小和最大操作

[英]Min and Max operations on enum values

Using C#, how can I take the min or max of two enum values?使用 C#,如何获取两个枚举值的最小值或最大值?

For example, if I have例如,如果我有

enum Permissions
{
    None,
    Read,
    Write,
    Full
}

is there a method that lets me do Helper.Max(Permissions.Read, Permissions.Full) and get Permissions.Full , for example?例如,有没有一种方法可以让我执行Helper.Max(Permissions.Read, Permissions.Full)并获取Permissions.Full

Enums implement IComparable so you can use:枚举实现IComparable以便您可以使用:

public static T Min<T>(T a, T b) where T : IComparable
{
    return a.CompareTo(b) <= 0 ? a : b;
}

Since enums are convertible to integer types, you can just do:由于枚举可以转换为整数类型,您可以这样做:

   var permissions1 = Permissions.None;
   var permissions2 = Permissions.Full;
   var maxPermission = (Permissions) Math.Max((int) permissions1, (int) permissions2);

Note that this could cause issues if your enum is based on an unsigned type, or a type longer than 32 bits (ie, long or ulong), but in that case you can just change the type you are casting the enums as to match the type declared in your enum.请注意,如果您的枚举基于无符号类型或长度超过 32 位的类型(即 long 或 ulong),这可能会导致问题,但在这种情况下,您可以更改您正在强制转换的枚举类型以匹配在您的枚举中声明的类型。

Ie, for an enum declared as:即,对于声明为的枚举:

enum Permissions : ulong
{
    None,
    Read,
    Write,
    Full
}

You would use:你会使用:

   var permissions1 = Permissions.None;
   var permissions2 = Permissions.Full;
   var maxPermission = (Permissions) Math.Max((ulong) permissions1, (ulong) permissions2);

can be called with 2 or more parameters可以使用 2 个或更多参数调用

    public static T GetMaxEnum<T>(params T[] enums) where T : struct, IConvertible
    {
        if (enums.Length < 2)
        {
            throw new InvalidEnumArgumentException();
        }
        return enums.Max();
    }

This is what I came up with because I couldn't find anything in .NET that did this.这就是我想出的,因为我在 .NET 中找不到任何可以做到这一点的东西。

public static class EnumHelper
{
    public static T Min<T>(T a, T b)
    {
        return (dynamic)a < (dynamic)b ? a : b;
    }

    public static T Max<T>(T a, T b)
    {
        return (dynamic)a > (dynamic)b ? a : b;
    }
}

I think you want something like this:我想你想要这样的东西:

public enum Enum1
{
    A_VALUE,
    B_VALUE,
    C_VALUE
}

public enum Enum2
{
    VALUE_1,
    VALUE_2,
    VALUE_3
}

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();

        Console.WriteLine(p.EnumMin<Enum1>());
        Console.WriteLine(p.EnumMax<Enum2>());

    }


    T EnumMin<T>()
    {
        T ret; ;
        Array x = Enum.GetValues(typeof(T));
        ret  = (T) x.GetValue(0);
        return ret;
    }

    T EnumMax<T>()
    {
        T ret; ;
        Array x = Enum.GetValues(typeof(T));
        ret = (T)x.GetValue(x.Length-1);
        return ret;
    }

}

There is a one-stop means for getting the min and max for any enumeration.有一种一站式方法可以获取任何枚举的最小值和最大值。 All it assumes is that the representation type is an int .它只假设表示类型是int

    public Tuple<int,int> GetMinMaxOfEnumeration<T>()
    {
        if (!typeof (T).IsEnum)
        {
            throw new ArgumentException("Type must be an enumeration");
        }
        var valuesAsInt = Enum.GetValues(typeof (T)).Cast<int>().OrderBy(n => n).ToArray();
        return new Tuple<int, int>(valuesAsInt.First(), valuesAsInt.Last());
    }

While this question is quite old, it shows up at the top for some searches I did, so here we go, with a little more detail than the existing answer:虽然这个问题很老,但它出现在我进行的一些搜索的顶部,所以我们在这里 go,比现有答案更详细一些:

Permissions p1 = Permissions.Read;
Permissions p2 = Permissions.Write;

var pMax = (Permissions)Math.Max( (int)p1, (int)p2 );

Alternatively in case the enum is long based:或者,如果枚举是基于长的:

var pMax = (Permissions)Math.Max( (long)p1, (long)p2 );

Why does this work?为什么这行得通?

  • enum values can be cast to int (or 'long'), which represents their position enum值可以转换为int (或“long”),代表它们的 position
  • An int can be cast back to an enum一个int可以转换回一个enum
  • Math.Max() apparently works on int Math.Max()显然适用于int

Sidenotes:旁注:

  • Appearently this also works for the mininum with Math.Min()显然这也适用于Math.Min()的最小值
  • IEnumerable.Max() and IEnumerable.Min() can be used if you need the maximum or minimum of more than two enum values (if you don't mind System.Linq ).如果您需要两个以上enum值的最大值或最小值(如果您不介意System.Linq ),则可以使用IEnumerable.Max()IEnumerable.Min() ) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM