What is the default value for enum variable?

前端 未结 3 965
花落未央
花落未央 2020-11-30 20:11

An enum variable, anyone know if it is always defaulting to the first element?

3条回答
  •  臣服心动
    2020-11-30 21:16

    You can use this snippet :-D

    using System;
    using System.Reflection;
    
    public static class EnumUtils
    {
        public static T GetDefaultValue()
            where T : struct, Enum
        {
            return (T)GetDefaultValue(typeof(T));
        }
    
        public static object GetDefaultValue(Type enumType)
        {
            var attribute = enumType.GetCustomAttribute(inherit: false);
            if (attribute != null)
                return attribute.Value;
    
            var innerType = enumType.GetEnumUnderlyingType();
            var zero = Activator.CreateInstance(innerType);
            if (enumType.IsEnumDefined(zero))
                return zero;
    
            var values = enumType.GetEnumValues();
            return values.GetValue(0);
        }
    }
    

    Example:

    using System;
    
    public enum Enum1
    {
        Foo,
        Bar,
        Baz,
        Quux
    }
    public enum Enum2
    {
        Foo  = 1,
        Bar  = 2,
        Baz  = 3,
        Quux = 0
    }
    public enum Enum3
    {
        Foo  = 1,
        Bar  = 2,
        Baz  = 3,
        Quux = 4
    }
    [DefaultValue(Enum4.Bar)]
    public enum Enum4
    {
        Foo  = 1,
        Bar  = 2,
        Baz  = 3,
        Quux = 4
    }
    
    public static class Program 
    {
        public static void Main() 
        {
            var defaultValue1 = EnumUtils.GetDefaultValue();
            Console.WriteLine(defaultValue1); // Foo
    
            var defaultValue2 = EnumUtils.GetDefaultValue();
            Console.WriteLine(defaultValue2); // Quux
    
            var defaultValue3 = EnumUtils.GetDefaultValue();
            Console.WriteLine(defaultValue3); // Foo
    
            var defaultValue4 = EnumUtils.GetDefaultValue();
            Console.WriteLine(defaultValue4); // Bar
        }
    }
    

提交回复
热议问题