![[C#] 6일차 - 32. 열거형 enum](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fda55QJ%2FbtqT6HAFIWJ%2FhrJ905fK3KmuVQ4FHnkco0%2Fimg.png)
[C#] 6일차 - 32. 열거형 enumC#/C#200제2021. 1. 21. 10:42
Table of Contents
열거형은 서로 관련 있는 상수들의 집합을 정의한 것.
숫자에 특정한 명칭을 붙여 쉽게 이해할 수 있는 용도로 사용된다
원소로 기술된 명칭을 기호 상수라고 부르며, 순서에 따라 default=0 부터 순서대로 정수값을 갖게 된다.
enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri}
기호상수의 값을 별도로 지정할 수 도 있다.
enum Day { Sat=1, Sun, Mon, Tue, Wed, Thu, Fri=10 };
열거형 값을 정수로 대입할 떄는 다음과 같이 (int)로 캐스팅한다.
int x = (int)Day.Sun;
enum문은 class안이나 namespace내에서만 선언될 수 있다.
다른곳에서는 Enum클래스에서 제공하는 GetValues()나 GetNames()를 가지고 꺼내 사용한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A032_Enum
{
class Program
{
enum Size { Short, Tall, Grande, Venti };
static int[] price = { 3300, 3800, 4300, 4800 };
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
enum Coffee { Short = 3300, Tall = 3800, Grande = 4300, Venti = 4800 };
static void Main(string[] args)
{
Console.WriteLine("커피 가격표");
for (int i = 0; i < 4; i++)
{
if (i == (int)Size.Short)
Console.WriteLine("{0,10} : {1:C}", Size.Short, price[i]);
else if(i == (int)Size.Tall)
Console.WriteLine("{0,10} : {1:C}", Size.Tall, price[i]);
else if (i == (int)Size.Grande)
Console.WriteLine("{0,10} : {1:C}", Size.Grande, price[i]);
else if (i == (int)Size.Venti)
Console.WriteLine("{0,10} : {1:C}", Size.Venti, price[i]);
}
Console.WriteLine("\n 커피 가격표(Enum interation)");
foreach(var size in Enum.GetValues(typeof(Size)))
{
Console.WriteLine("{0,10} : {1:C}", size, price[(int)size]);
}
Console.WriteLine("\n Colors Enum interation");
foreach (var color in Enum.GetValues(typeof(Colors)))
{
Console.WriteLine("{0,10} : {1}", color, Convert.ToInt32(color));
}
Console.WriteLine("\n 커피 가격표(Enum iteration with value)");
foreach (var coffee in Enum.GetValues(typeof(Coffee)))
{
Console.WriteLine("{0,10} : {1:C}", coffee, Convert.ToInt32(coffee));
}
}
}
}
반응형
'C# > C#200제' 카테고리의 다른 글
[C#] 6일차 - 34. 값 형식과 참조 형식, ref 키워드 (0) | 2021.01.21 |
---|---|
[C#] 6일차 - 33. 상수, const와 readonly (0) | 2021.01.21 |
[C#] 5일차 (문자, 문자열 정리) (0) | 2021.01.20 |
[C#] 4일차 ( try~catch문, 각종 연산자 ) (0) | 2021.01.19 |
[C#] 3일차 ( Format과 연산자 처리) (0) | 2021.01.18 |
@반나무 :: 반나무_뿌리
3년차 WPF 개발자입니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!