본문 바로가기
C#/Common

[C#] Enum foreach - Enum(열거형) 반복문 사용법

by 샤나엘 2018. 4. 5.
반응형

C# enum으로 정의된 값들에 대해 반복문으로 사용하는 방법입니다.


 

enum에 정의된 값들에 대해서 반복문으로 사용해야 하는 경우가 생기는데, 아래 구문을 통해서 사용하실 수 있습니다.

 

Enum.GetValues(Type enumType)


 

 

[사용예제]

 

아래처럼 enum 구문을 작성해서

1
2
3
4
5
6
7
8
9
    public enum TEXT
    {
        A,
        B,
        C,
        D,
        E,
        F
    }   

foreach 를 통해 값을 출력하는 예제입니다.

 

1
foreach (TEXT text in Enum.GetValues(typeof(TEXT)))

 

[전체소스]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            Label lbl = new Label();
            lbl.Dock = DockStyle.Fill;
            this.Controls.Add(lbl);
 
            foreach (TEXT text in Enum.GetValues(typeof(TEXT)))
            {
                lbl.Text += text + "\n";
            }
        }
    }
 
    public enum TEXT
    {
        A,
        B,
        C,
        D,
        E,
        F
    }   
}

 


[실행결과]

 

 


반응형

'C# > Common' 카테고리의 다른 글

C# Dictionary sort 정렬하는 방법  (0) 2021.06.07
[C#] Dictionary 사용예제  (0) 2018.04.02
[C#] DataTable 사용법  (0) 2018.03.28
[C#] Color  (0) 2018.03.20
[C#] Random Class 사용  (0) 2018.03.20

댓글