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

前端 未结 13 2695
迷失自我
迷失自我 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条回答
  •  猫巷女王i
    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 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();
                foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
                {
                    dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
                }
            } 
            #endregion
    

提交回复
热议问题