Getting the max value of an enum

后端 未结 11 2297
旧时难觅i
旧时难觅i 2020-12-07 13:42

How do you get the max value of an enum?

11条回答
  •  Happy的楠姐
    2020-12-07 14:02

    According to Matt Hamilton's answer, I thought on creating an Extension method for it.

    Since ValueType is not accepted as a generic type parameter constraint, I didn't find a better way to restrict T to Enum but the following.

    Any ideas would be really appreciated.

    PS. please ignore my VB implicitness, I love using VB in this way, that's the strength of VB and that's why I love VB.

    Howeva, here it is:

    C#:

    static void Main(string[] args)
    {
        MyEnum x = GetMaxValue(); //In newer versions of C# (7.3+)
        MyEnum y = GetMaxValueOld();  
    }
    
    public static TEnum GetMaxValue()
      where TEnum : Enum
    {
         return Enum.GetValues(typeof(TEnum)).Cast().Max();
    }
    
    //When C# version is smaller than 7.3, use this:
    public static TEnum GetMaxValueOld()
      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().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
    

提交回复
热议问题