C# 获取枚举的最大值

C# 获取枚举的最大值,c#,enums,C#,Enums,如何获取枚举的最大值?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(); //给定此枚举: 公众谘询委员会 { 嘶嘶声=3, 巴=1, 爆炸

如何获取枚举的最大值?

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();
//给定此枚举:
公众谘询委员会
{
嘶嘶声=3,
巴=1,
爆炸=2
}
//这会起泡
var lastFoo=Enum.GetValues(typeof(Foo)).Cast().Last();
编辑

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

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

。。。当某些枚举值为负数时,这将起作用。

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

法律:

enum SomeEnum
{
    Fizz = 42
}

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

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

由于
ValueType
不被接受为泛型类型参数约束,因此我没有找到更好的方法将
t
限制为
Enum
,但有以下内容

任何想法都将不胜感激

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

Howeva,这是:

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

因此,在Visual Studio中的VB.Net项目中,我可以键入“System.Enum”。intellisense带来了各种好处

其中一个方法是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")

'''''''

使用上一个函数无法获取最大值。可以使用“最大”功能。比如:

 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);
        }
    }
类程序
{
enum enum1{1,2,2,3};
枚举2{s1=10,s2=8,s3,s4};
枚举3{f1=-1,f2=3,f3=-3,f4};
静态void Main(字符串[]参数)
{
TestMaxEnumValue(typeof(enum1));
TestMaxEnumValue(typeof(enum2));
TestMaxEnumValue(typeof(enum3));
}
静态void TestMaxEnumValue(类型enumType)
{
Enum.GetValues(enumType).Cast().ToList().ForEach(项=>
Console.WriteLine(item.ToString());
int maxValue=Enum.GetValues(enumType.Cast().Max();
WriteLine(“{0}的最大值为{1}”,enumType.Name,maxValue);
}
}

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

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());        
    }
}
公共静态类枚举扩展
{
公共静态int Max(此枚举枚举类型)
{           
返回Enum.GetValues(enumType.GetType()).Cast().Max();
}
}
班级计划
{
enum enum1{1,2,2,3};
枚举2{s1=10,s2=8,s3,s4};
枚举3{f1=-1,f2=3,f3=-3,f4};
静态void Main(字符串[]参数)
{
Console.WriteLine(enum1.one.Max());
}
}

与Matthew J Sullivan就C#达成一致:

我真的不知道为什么会有人想使用:

   Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();
Enum.GetValues(typeof(MyEnum)).Cast().Last();
…逐字逐句,从语义上讲,它似乎没有那么有意义?(有不同的方法总是好的,但我看不到后者的好处。)

在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   
输入Foo=
|起泡=3
|爆炸=2
//用于将枚举转换为序列的辅助函数。这对于迭代也很有用。
//stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c

我同意马特的回答。如果您只需要min和max int值,那么您可以按如下操作

最大值:

Enum.GetValues(typeof(Foo)).Cast<int>().Max();
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
Enum.GetValues(typeof(Foo)).Cast().Max();
最小值:

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

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

枚举值{
一,,
二,,
树,
完,,
}
对于(值i=0;i

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

当需要枚举的最小值和最大值时,我使用了以下方法。 我只是将最小值设置为枚举中的最小值,最大值设置为枚举中的最大值,作为枚举值本身

public enum ChannelMessageTypes : byte
{
    Min                 = 0x80, // Or could be: Min = NoteOff
    NoteOff             = 0x80,
    NoteOn              = 0x90,
    PolyKeyPressure     = 0xA0,
    ControlChange       = 0xB0,
    ProgramChange       = 0xC0,
    ChannelAfterTouch   = 0xD0,
    PitchBend           = 0xE0,
    Max                 = 0xE0  // Or could be: Max = PitchBend
}

// I use it like this to check if a ... is a channel message.
if(... >= ChannelMessageTypes.Min || ... <= ChannelMessages.Max)
{
    Console.WriteLine("Channel message received!");
}
公共枚举ChannelMessageType:字节
{
Min=0x80,//或者可以是:Min=NoteOff
NoteOff=0x80,
注on=0x90,
PolyKeyPressure=0xA0,
ControlChange=0xB0,
程序更改=0xC0,
ChannelAfterTouch=0xD0,
俯仰弯曲=0xE0,
Max=0xE0//或者可以是:Max=PitchBend
}
//我用它来检查一个。。。是一个频道消息。

if(…>=ChannelMessageTypes.Min | |…很好。利用:“数组的元素按枚举常量的二进制值排序。”从我开始,我觉得这真的很琐碎,但给出了一个优雅的解决方案。此外,如果您想获得枚举值,请使用Convert.ToInt32()之后。这是谷歌结果。如果你要使用LINQ,为什么不使用Max(),它更清晰,而且不依赖于“似乎”?它性能更好,但前提是枚举的值不匹配
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
public enum ChannelMessageTypes : byte
{
    Min                 = 0x80, // Or could be: Min = NoteOff
    NoteOff             = 0x80,
    NoteOn              = 0x90,
    PolyKeyPressure     = 0xA0,
    ControlChange       = 0xB0,
    ProgramChange       = 0xC0,
    ChannelAfterTouch   = 0xD0,
    PitchBend           = 0xE0,
    Max                 = 0xE0  // Or could be: Max = PitchBend
}

// I use it like this to check if a ... is a channel message.
if(... >= ChannelMessageTypes.Min || ... <= ChannelMessages.Max)
{
    Console.WriteLine("Channel message received!");
}