Using an enum as an array index in C#

前端 未结 10 934
死守一世寂寞
死守一世寂寞 2020-12-28 14:17

I want to do the same as in this question, that is:

enum DaysOfTheWeek {Sunday=0, Monday, Tuesday...};
string[] message_array = new string[number_of_items_at         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 14:22

    You can always do some extra mapping to get an array index of an enum value in a consistent and defined way:

    int ArrayIndexFromDaysOfTheWeekEnum(DaysOfWeek day)
    {
       switch (day)
       {
         case DaysOfWeek.Sunday: return 0;
         case DaysOfWeek.Monday: return 1;
         ...
         default: throw ...;
       }
    }
    

    Be as specific as you can. One day someone will modify your enum and the code will fail because the enum's value was (mis)used as an array index.

提交回复
热议问题