Getting the max value of an enum

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

How do you get the max value of an enum?

11条回答
  •  無奈伤痛
    2020-12-07 14:02

    Use the Last function could not get the max value. Use the "max" function could. Like:

     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().ToList().ForEach(item =>
                    Console.WriteLine(item.ToString()));
    
                int maxValue = Enum.GetValues(enumType).Cast().Max();     
                Console.WriteLine("The max value of {0} is {1}", enumType.Name, maxValue);
            }
        }
    

提交回复
热议问题