Enum with methods for functionality (Combine Class / Enum)

后端 未结 2 1717

I may miss some sort of point here, if that\'s the case - please include that discussion as a part of my question :).

This is a shortened down and renamed sample of a wo

2条回答
  •  佛祖请我去吃肉
    2021-02-03 19:53

    If you don't mind a little more writing you can make extension methods to expand the interface of the enum.

    e.g.

    public enum TimeUnit
    {
       Second,
       Minute,
       Hour,
       Day,
       Year,
       /* etc */
    }
    public static class TimeUnitExtensions
    {
        public static long InTicks(this TimeUnit myUnit)
        {
             switch(myUnit)
             {
               case TimeUnit.Second:
                   return TimeSpan.TicksPerSecond;
               case TimeUnit.Minute:
                   return TimeSpan.TicksPerMinute;
                /* etc */
             }
        }
    }
    

    This can add "instance" methods to your enums. It's a bit more verbose than mostly liked, though.

    Remember though that an enum should be treated mostly as a named value.

提交回复
热议问题