小编典典

如何遍历 C# 中的所有枚举值?

javascript

public enum Foos
{
    A,
    B,
    C
}

有没有办法循环遍历 的可能值Foos

基本上?

foreach(Foo in Foos)

阅读 293

收藏
2022-02-21

共1个答案

小编典典

是的,您可以使用GetValue‍‍‍s‍ 方法:

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>();
2022-02-21