foreach() для enum
Подскажите, как организовать foreach() для элементов enum ? Пример того, что хочу сделать:
Если именно foreach() , то:
Если мощность перечисления известна (а она, разумеется, известна — главное, не забывать подправлять константу при изменении перечисления), то можно, например, так:
Это сработает, потому как по умолчанию элементам перечисления соответствуют целые числа от 0 до N-1 (если продолжите операцию fruit++, обнаружите, что никакой ошибки не произойдет, а fruit начнёт принимать неименованные значения 3, 4, . )
Как перебрать enum c
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
- ProfileText
- Sign in
Answered by:
Question
I can foreach all static variables this:
How can I foreach all enum types?
Answers
You can get all public enums in the executing assembly like this:
- Marked as answer by Robert Varga 2 Thursday, March 28, 2013 12:45 PM
All replies
Take a look at the answer to this Stackoverflow thread.
private void checkFullTable(Type e)
<
MessageBox.Show(e.Name);
foreach (string str in Enum.GetNames(e))
<
MessageBox.Show(str.ToString());
>
>
I would like just foreach all enum type
Foreach (Enum e in all_class_enum)
<
MessageBox.Show(e.name);
Foreach(string s in e)
<
MessageBox.Show(s);
>
>
Just like that show all enum name, and enum’s data. Because I have more like 100 enum type, and i would like foreach all in 1 command.
How to loop through all enum values in C#? [duplicate]
Is there a way to loop through the possible values of Foos ?
8 Answers 8
Yes you can use the GetValues method:
Or the typed version:
I long ago added a helper function to my private library for just such an occasion:
UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I’d do it differently now. These days I’d write:
![]()
Yes. Use GetValues() method in System.Enum class.
![]()
-
The Overflow Blog
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to enumerate an enum in C#
Get Educative’s popular interview prep course for free.
Overview
An Enum is a user-defined value type in C#, which represents a group of constants. It can be created in a class, structure, or namespace.
Enumerating an enum
Enumerating means we loop through the elements of an enum . There are two methods to enumerate an enum :
- Using the Enum.GetNames() method
- Using the Enum.GetValues() method
The Enum.GetNames() method
This approach will loop through the elements of the enum and get the names of constants from the enum to an array. After that, it uses a foreach loop to print this array.