首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取枚举的最大值

获取枚举的最大值
EN

Stack Overflow用户
提问于 2008-10-15 00:59:34
回答 8查看 98.8K关注 0票数 170

如何获取枚举的最大值?

EN

回答 8

Stack Overflow用户

发布于 2009-08-20 00:52:29

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

由于ValueType不被接受为泛型类型参数约束,所以我没有找到更好的方法来将T限制为Enum,但是如下所示。

任何想法都会非常感谢。

PS。请忽略我对VB的含蓄,我喜欢以这种方式使用VB,这就是VB的力量所在,也是我热爱VB的原因。

您好,这就是:

C#:

static void Main(string[] args)
{
    MyEnum x = GetMaxValue<MyEnum>(); //In newer versions of C# (7.3+)
    MyEnum y = GetMaxValueOld<MyEnum>();  
}

public static TEnum GetMaxValue<TEnum>()
  where TEnum : Enum
{
     return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();
}

//When C# version is smaller than 7.3, use this:
public static TEnum GetMaxValueOld<TEnum>()
  where TEnum : IComparable, IConvertible, IFormattable
{
    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
票数 22
EN

Stack Overflow用户

发布于 2008-10-15 08:13:32

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

法律:

enum SomeEnum
{
    Fizz = 42
}

public static void SomeFunc()
{
    SomeEnum e = (SomeEnum)5;
}
票数 13
EN

Stack Overflow用户

发布于 2009-11-03 16:19:49

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

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());        
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/203377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档