如何遍历 C# 中的所有枚举值? [英] How to loop through all enum values in C#?

查看:66
本文介绍了如何遍历 C# 中的所有枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经有了答案:
如何在 C# 中枚举枚举? 26 个回答

public enum Foos
{
    A,
    B,
    C
}

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

Is there a way to loop through the possible values of Foos?

基本上?

foreach(Foo in Foos)

推荐答案

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

Yes you can use the ‍GetValue‍‍‍s method:

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

或打字版本:

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>();
    }
}

用法:

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

这篇关于如何遍历 C# 中的所有枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆