Choosing the default value of an Enum type without having to change values

前端 未结 13 2578
迷失自我
迷失自我 2020-12-04 07:46

In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The

相关标签:
13条回答
  • 2020-12-04 08:30

    The default is the first one in the definition. For example:

    public enum MyEnum{His,Hers,Mine,Theirs}
    
    Enum.GetValues(typeOf(MyEnum)).GetValue(0);
    

    This will return His

    0 讨论(0)
  • 2020-12-04 08:31

    An enum's default is whatever enumeration equates to zero. I don't believe this is changeable by attribute or other means.

    (MSDN says: "The default value of an enum E is the value produced by the expression (E)0.")

    0 讨论(0)
  • 2020-12-04 08:33

    If zero doesn't work as the proper default value, you can use the component model to define a workaround for the enum:

    [DefaultValue(None)]
    public enum Orientation
    {
         None = -1,
         North = 0,
         East = 1,
         South = 2,
         West = 3
     }
    
    public static class Utilities
    {
        public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
        {
            Type t = typeof(TEnum);
            DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
            if (attributes != null &&
                attributes.Length > 0)
            {
                return (TEnum)attributes[0].Value;
            }
            else
            {
                return default(TEnum);
            }
        }
    }
    

    and then you can call:

    Orientation o = Utilities.GetDefaultValue<Orientation>();
    System.Diagnostics.Debug.Print(o.ToString());
    

    Note: you will need to include the following line at the top of the file:

    using System.ComponentModel;
    

    This does not change the actual C# language default value of the enum, but gives a way to indicate (and get) the desired default value.

    0 讨论(0)
  • 2020-12-04 08:33

    You can't, but if you want, you can do some trick. :)

        public struct Orientation
        {
            ...
            public static Orientation None = -1;
            public static Orientation North = 0;
            public static Orientation East = 1;
            public static Orientation South = 2;
            public static Orientation West = 3;
        }
    

    usage of this struct as simple enum.
    where you can create p.a == Orientation.East (or any value that you want) by default
    to use the trick itself, you need to convert from int by code.
    there the implementation:

            #region ConvertingToEnum
            private int val;
            static Dictionary<int, string> dict = null;
    
            public Orientation(int val)
            {
                this.val = val;
            }
    
            public static implicit operator Orientation(int value)
            {
                return new Orientation(value - 1);
            }
    
            public static bool operator ==(Orientation a, Orientation b)
            {
                return a.val == b.val;
            }
    
            public static bool operator !=(Orientation a, Orientation b)
            {
                return a.val != b.val;
            }
    
            public override string ToString()
            {
                if (dict == null)
                    InitializeDict();
                if (dict.ContainsKey(val))
                    return dict[val];
                return val.ToString();
            }
    
            private void InitializeDict()
            {
                dict = new Dictionary<int, string>();
                foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
                {
                    dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
                }
            } 
            #endregion
    
    0 讨论(0)
  • 2020-12-04 08:35

    If you define the Default enum as the enum with the smallest value you can use this:

    public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }
    
    var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];
    
    firstEnum == Mine.
    

    This doesn't assume that the enum has a zero value.

    0 讨论(0)
  • 2020-12-04 08:35
    [DefaultValue(None)]
    public enum Orientation
    {
        None = -1,
        North = 0,
        East = 1,
        South = 2,
        West = 3
    }
    

    Then in the code you can use

    public Orientation GetDefaultOrientation()
    {
       return default(Orientation);
    } 
    
    0 讨论(0)
提交回复
热议问题