본문 바로가기
프로그래밍

[C#] enum과 문자열 치환/변환 <속성(어트리뷰트)을 이용한 간단 치환 방법>

by 건우아빠유리남편 2011. 2. 25.
반응형

public enum animal
{
[Description("똥꼬양이")]
cat = 1,
[Description(똥꾸 멍멍멍멍멍!!~)]
dog = 2,
[Description(똥 뙈 지)]
pig = 3,
}

public static class EnumHelper
{
public static string GetDescription(Enum e)
{
Type type = e.GetType();
MemberInfo[] memInfo = type.GetMember(e.ToString());
if(memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if(attrs != null & attrs.Length > 0)
{
return((DescriptionAttribute)attrs[0]).Description;
}
}
return e.ToString();
}
}

using System.ComponentModel;        //해줘야지
using System.Reflection;

기존 enum.Parser로 하던 방법에서는 띄어쓰기 및 한글로 가져오기가 힘들었지비... (한글로 코딩해노면 쌍싸다구 얻어맞음)
그러니께리 리플렉션 이용한 요 방법이 지금은 좋을듯...

좀 더 자세한 내용은
심재운님 티스토리로 가야함

출처 : 심재운님 티스토리
반응형

댓글