How to enumerate an enum

后端 未结 29 1900
深忆病人
深忆病人 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:43

    I use ToString() then split and parse the spit array in flags.

    [Flags]
    public enum ABC {
       a = 1,
       b = 2,
       c = 4
    };
    
    public IEnumerable Getselected (ABC flags)
    {
       var values = flags.ToString().Split(',');
       var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
       return enums;
    }
    
    ABC temp= ABC.a | ABC.b;
    var list = getSelected (temp);
    foreach (var item in list)
    {
       Console.WriteLine(item.ToString() + " ID=" + (int)item);
    }
    

提交回复
热议问题