Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c# - 如何遍历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)
  ask by divinci translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...