你可以遍历所有的枚举值?


This question already has an answer here:
How to enumerate an enum? 14 answers

public enum Foos
{
    A,
    B,
    C
}

有没有办法循环Foos的可能值?

基本上?

foreach(Foo in Foos)

是的,您可以使用GetValues方法

var values = Enum.GetValues(typeof(Foos));

或者输入版本

var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();

我很久以前就给我的私人图书馆增加了一个帮手功能

public static class EnumUtil {
  public static IEnumerable<T> GetValues<T>() {
    return Enum.GetValues(typeof(T)).Cast<T>();
  }
}

用法:

var values = EnumUtil.GetValues<Foos>();

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

未经作者同意,本文严禁转载,违者必究!