블로그 이미지
Every unexpected event is a path to learning for you. blueasa

카테고리

분류 전체보기 (2797)
Unity3D (853)
Programming (479)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (185)
협업 (61)
3DS Max (3)
Game (12)
Utility (68)
Etc (98)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (55)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday

Summary

Enums are a powerful construction in C# and other programming languages when you are working with finite sets such as fruits, days of the week or colors. Visual Studio's Intellisense is very nice with Enums because it lists all the options for the programmer to choose from. But quite often you want to print enums, compare int values, or serialize an enum--and then you have to do some conversions.The following method may be run in the code-behind file of an ASPX page where you have added a Label control named lblOutput. However, this technique will work in any C# program, not just ASP.NET.

Example: Convert string to Enum instance

public void EnumInstanceFromString()
{
   // The .NET Framework contains an Enum called DayOfWeek.
   // Let's generate some Enum instances from strings.

   DayOfWeek wednesday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");
   DayOfWeek sunday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "sunday", true);
   DayOfWeek tgif = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "FRIDAY", true);

   lblOutput.Text = wednesday.ToString() 
      + ".  Int value = " + ((int)wednesday).ToString() + "<br>";
   lblOutput.Text += sunday.ToString() 
      + ".  Int value = " + ((int)sunday).ToString() + "<br>";
   lblOutput.Text += tgif.ToString() 
      + ".  Int value = " + ((int)tgif).ToString() + "<br>";

}
The Enum.Parse method takes two or three arguments. The first is the type of the enum you want to create as output. The second field is the string you want to parse. Without a third input, the case of the input string must match an enum instance or the conversion fails. But the third input indicates whether to ignore case. If true, than wEdNEsDAy will still get converted successfully.

Example: Output

Wednesday. Int value = 3
Sunday. Int value = 0
Friday. Int value = 5

출처 :  http://www.cambiaresearch.com/articles/47/convert-string-to-enum-instance
반응형

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

Nullable 형식 사용  (0) 2012.01.19
MeasureString(문자열 길이 체크)  (0) 2012.01.17
문자열이 숫자 값을 나타내는지 확인  (0) 2011.12.16
Operator Overloading in C#  (2) 2011.12.05
Force property update in propertygrid  (0) 2011.11.29
Posted by blueasa
, |