如何遍历C#中的所有枚举值? [重复]

本文翻译自:How to loop through all enum values in C#? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:
How do I enumerate an enum in C#? 如何在C#中枚举枚举? 26 answers 26个答案

public enum Foos
{
    A,
    B,
    C
}

Is there a way to loop through the possible values of Foos ? 有没有办法循环Foos的可能值?

Basically? 基本上?

foreach(Foo in Foos)

#1楼

参考:https://stackoom.com/question/44wN/如何遍历C-中的所有枚举值-重复


#2楼

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

#3楼

Yes you can use the ‍ GetValue‍‍‍s method: 是的,你可以使用GetValue‍‍‍s方法:

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

Or the typed version: 或打字版本:

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

I long ago added a helper function to my private library for just such an occasion: 我很久以前就在这样的场合为我的私人图书馆添加了一个辅助函数:

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

Usage: 用法:

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

#4楼

Yes. 是。 Use GetValues() method in System.Enum class. System.Enum类中使用GetValues()方法。


#5楼

foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
   Console.WriteLine(val);
}

Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum 感谢Jon Skeet: http//bytes.com/groups/net-c/266447-how-loop-each-items-enum


#6楼

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    ...
}
发布了0 篇原创文章 · 获赞 73 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/w36680130/article/details/105240971
今日推荐