如何获得枚举的最大值?

有帮助吗?

解决方案

Enum.GetValues()似乎按顺序返回值,所以你可以这样做:

// given this enum:
public enum Foo
{
    Fizz = 3, 
    Bar = 1,
    Bang = 2
}

// this gets Fizz
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();

修改

对于那些不愿意阅读评论的人:你也可以这样做:

var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();

...当你的一些枚举值为负时,它会起作用。

其他提示

我同意马特的回答。如果只需要min和max int值,那么可以按如下方式进行。

<强>最大:

Enum.GetValues(typeof(Foo)).Cast<int>().Max();

<强>最小

Enum.GetValues(typeof(Foo)).Cast<int>().Min();

根据Matt Hamilton的回答,我想为它创建一个扩展方法。

由于ValueType不被接受作为通用类型参数约束,我没有找到更好的方法将T限制为Enum但是以下内容。

任何想法都会非常感激。

PS。请忽略我的VB隐含性,我喜欢用这种方式使用VB,这就是VB的优点,这就是我喜欢VB的原因。

Howeva,现在是:

C#:

static void Main(string[] args)
{
    MyEnum x = GetMaxValue<MyEnum>();
}

public static TEnum GetMaxValue<TEnum>() 
    where TEnum : IComparable, IConvertible, IFormattable
    //In C#>=7.3 substitute with 'where TEnum : Enum', and remove the following check:
{
    Type type = typeof(TEnum);

    if (!type.IsSubclassOf(typeof(Enum)))
        throw new
            InvalidCastException
                ("Cannot cast '" + type.FullName + "' to System.Enum.");

    return (TEnum)Enum.ToObject(type, Enum.GetValues(type).Cast<int>().Last());
}

enum MyEnum
{
    ValueOne,
    ValueTwo
}

VB:

Public Function GetMaxValue _
    (Of TEnum As {IComparable, IConvertible, IFormattable})() As TEnum

    Dim type = GetType(TEnum)

    If Not type.IsSubclassOf(GetType([Enum])) Then _
        Throw New InvalidCastException _
            ("Cannot cast '" & type.FullName & "' to System.Enum.")

    Return [Enum].ToObject(type, [Enum].GetValues(type) _
                        .Cast(Of Integer).Last)
End Function

这有点挑剔,但任何枚举的实际最大值是Int32.MaxValue(假设它是从int派生的枚举)。将任何Int32值转换为任何枚举是完全合法的,无论它是否实际声明具有该值的成员。

法律:

enum SomeEnum
{
    Fizz = 42
}

public static void SomeFunc()
{
    SomeEnum e = (SomeEnum)5;
}

经过另一次尝试后,我得到了这个扩展方法:

public static class EnumExtension
{
    public static int Max(this Enum enumType)
    {           
        return Enum.GetValues(enumType.GetType()).Cast<int>().Max();             
    }
}

class Program
{
    enum enum1 { one, two, second, third };
    enum enum2 { s1 = 10, s2 = 8, s3, s4 };
    enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };

    static void Main(string[] args)
    {
        Console.WriteLine(enum1.one.Max());        
    }
}

使用Last函数无法获取最大值。使用<!> quot; max <!> quot;功能可以。像:

 class Program
    {
        enum enum1 { one, two, second, third };
        enum enum2 { s1 = 10, s2 = 8, s3, s4 };
        enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };

        static void Main(string[] args)
        {
            TestMaxEnumValue(typeof(enum1));
            TestMaxEnumValue(typeof(enum2));
            TestMaxEnumValue(typeof(enum3));
        }

        static void TestMaxEnumValue(Type enumType)
        {
            Enum.GetValues(enumType).Cast<Int32>().ToList().ForEach(item =>
                Console.WriteLine(item.ToString()));

            int maxValue = Enum.GetValues(enumType).Cast<int>().Max();     
            Console.WriteLine("The max value of {0} is {1}", enumType.Name, maxValue);
        }
    }

与Matthew J Sullivan达成协议,C#:

   Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);

我真的不确定为什么有人想要使用:

   Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();

......从语义上讲,逐字逐句地说它似乎没那么有意义吗? (总是很好,有不同的方式,但我没有看到后者的好处。)

有一些方法可以在System.Enum下获取有关枚举类型的信息。

因此,在Visual Studio的VB.Net项目中,我可以输入<!> quot; System.Enum。<!> quot;并且智能感知带来了各种各样的善良。

一个方法特别是System.Enum.GetValues(),它返回枚举值的数组。一旦你有阵列,你应该能够做任何适合你特定情况的事情。

在我的例子中,我的枚举值从零开始并没有跳过任何数字,所以要获得我的枚举的最大值,我只需要知道数组中有多少元素。

VB.Net代码片段:

'''''''

Enum MattType
  zerothValue         = 0
  firstValue          = 1
  secondValue         = 2
  thirdValue          = 3
End Enum

'''''''

Dim iMax      As Integer

iMax = System.Enum.GetValues(GetType(MattType)).GetUpperBound(0)

MessageBox.Show(iMax.ToString, "Max MattType Enum Value")

'''''''

在F#中,使用辅助函数将枚举转换为序列:

type Foo =
    | Fizz  = 3
    | Bang  = 2

// Helper function to convert enum to a sequence. This is also useful for iterating.
// stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c
let ToSeq (a : 'A when 'A : enum<'B>) =
    Enum.GetValues(typeof<'A>).Cast<'B>()

// Get the max of Foo
let FooMax = ToSeq (Foo()) |> Seq.max   

运行它......

> type Foo = | Fizz = 3 | Bang = 2
> val ToSeq : 'A -> seq<'B> when 'A : enum<'B>
> val FooMax : Foo = Fizz

编译器不需要when 'A : enum<'B>作为定义,但是对于ToSeq的任何使用都是必需的,即使是有效的枚举类型也是如此。

它并非在所有情况下都可用,但我经常自己定义最大值:

enum Values {
  one,
  two,
  tree,
  End,
}

for (Values i = 0; i < Values.End; i++) {
  Console.WriteLine(i);
}

var random = new Random();
Console.WriteLine(random.Next((int)Values.End));

当你在枚举中使用自定义值时,这当然不起作用,但通常它可以是一个简单的解决方案。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top