如何遍历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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值