Using an enum as an array index in C#

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

    Since C# 7.3 it has been possible to use System.Enum as a constraint on type parameters. So the nasty hacks in the some of the other answers are no longer required.

    Here's a very simple ArrayByEum class that does exactly what the question asked.

    Note that it will waste space if the enum values are non-contiguous, and won't cope with enum values that are too large for an int. I did say this example was very simple.

    /// An array indexed by an Enum
    /// Type stored in array
    /// Indexer Enum type
    public class ArrayByEnum : IEnumerable where U : Enum // requires C# 7.3 or later
    {
      private readonly T[] _array;
      private readonly int _lower;
    
      public ArrayByEnum()
      {
        _lower = Convert.ToInt32(Enum.GetValues(typeof(U)).Cast().Min());
        int upper = Convert.ToInt32(Enum.GetValues(typeof(U)).Cast().Max());
        _array = new T[1 + upper - _lower];
      }
    
      public T this[U key]
      {
        get { return _array[Convert.ToInt32(key) - _lower]; }
        set { _array[Convert.ToInt32(key) - _lower] = value; }
      }
    
      public IEnumerator GetEnumerator()
      {
        return Enum.GetValues(typeof(U)).Cast().Select(i => this[i]).GetEnumerator();
      }
    }
    

    Usage:

    ArrayByEnum myArray = new ArrayByEnum();
    myArray[MyEnum.First] = "Hello";
    
    myArray[YourEnum.Other] = "World"; // compiler error
    

提交回复
热议问题