C# - 열거형 변환


열거형을 문자열로

enum    test{aa, bb, cc};
string   s;
test     Enumtest  =   test.aa;

s = (string)aa              (X) 
s = Convert.Tostring(aa);   (O)
s = aa.Tostring();          (O)

문자열을 열거형으로

(열거형)Enum.Parse(typeof(열거형), 열거형값문자열); 을 이용한다.
typeof()연산자는 주어진 피연산자의 형식을 돌려준다.

enum    test{aa, bb, cc};
string   s = "aa";
test     aa  =  (test)Enum.Parse(typeof(test), aa);

여기서 중요한것은 문자열값이 해당 열거형의 값들과 동일해야한다.(대소문자구분)

열거형 갯수

public enum enAllow { SchoolID , PW , Kind , SchYears , GradeID , Ver , IP, Msg};
int count = Enum.GetValues(typeof(enAllow)).Length;

foreach로 탐색

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

string s = Enum.GetName(typeof(Days), 4);
Console.WriteLine(s);

Console.WriteLine("The values of the Days Enum are:");
foreach (int i in Enum.GetValues(typeof(Days)))
    Console.WriteLine(i);

Console.WriteLine("The names of the Days Enum are:");
foreach (string str in Enum.GetNames(typeof(Days)))
    Console.WriteLine(str);

 

 

 

사용자 삽입 이미지

광고

댓글 남기기