How to enumerate an enum

后端 未结 29 1829
深忆病人
深忆病人 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:37

    My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:

    public static List GetEnumValues() where T : new() {
        T valueType = new T();
        return typeof(T).GetFields()
            .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
            .Distinct()
            .ToList();
    }
    
    public static List GetEnumNames() {
        return typeof (T).GetFields()
            .Select(info => info.Name)
            .Distinct()
            .ToList();
    }
    
    • If anyone knows how to get rid of the T valueType = new T(), I'd be happy to see a solution.

    A call would look like this:

    List result = Utils.GetEnumValues();
    

提交回复
热议问题