How to enumerate an enum

后端 未结 29 1891
深忆病人
深忆病人 2020-11-22 01:14

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{         


        
29条回答
  •  后悔当初
    2020-11-22 01:38

    If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:

    public static T[] GetEnumValues() where T : struct, IComparable, IFormattable, IConvertible
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
        }
        return Enum.GetValues(typeof(T)) as T[];
    }
    

    And you can use it like below:

    static readonly YourEnum[] _values = GetEnumValues();
    

    Of course you can return IEnumerable, but that buys you nothing here.

提交回复
热议问题