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

查看:779
本文介绍了如何遍历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)


推荐答案

是的,您可以使用‍ < a href = https://docs.microsoft.com/zh-cn/dotnet/api/system.enum.getvalues rel = noreferrer> 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天全站免登陆