Using an enum as an array index in C#

前端 未结 10 809
死守一世寂寞
死守一世寂寞 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:23

    For future reference the above problem can be summarized as follows:

    I come from Delphi where you can define an array as follows:

    type
      {$SCOPEDENUMS ON}
      TDaysOfTheWeek = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
    
      TDaysOfTheWeekStrings = array[TDaysOfTheWeek];
    

    Then you can iterate through the array using Min and Max:

    for Dow := Min(TDaysOfTheWeek) to Max(TDaysOfTheWeek) 
      DaysOfTheWeekStrings[Dow] := '';
    

    Though this is quite a contrived example, when you are dealing with array positions later in the code I can just type DaysOfTheWeekStrings[TDaysOfTheWeek.Monday]. This has the advantage of the fact that I should the TDaysOfTheWeek increase in size then I do not have to remember the new size of the array etc..... However back to the C# world. I have found this example C# Enum Array Example.

提交回复
热议问题