Enum을 String에서 변환 하기



 환경 설정에서는 흔히 XML로 저정되어 있어서 일차적으로 읽는 값이 String으로 되어 있다. 그 값으로 Enum 타입의 값으로 변경하기 위해서는 값을 switch 구문이나 if 문으로 구분해서 변환해야 만 했었다. 그렇지만 .Net Framework 4에서 Enum의 Parse, TryParse를 통해서 쉽게 변환할 수 있도록 지원하고 있다. 아래 예제 코드로 확인해 보자 (Enum.Parse는 1.1부터 지원되었음)


var type = EnumType.None;
 
// Encryption 변환되는지 테스트
if (!Enum.TryParse("Encryption"out type&& type == EnumType.Encryption)
{
    throw new InvalidCastException("LdapAuthenticationType값이 올바르지 않습니다. 다시 확인하여 주시기 바랍니다.");
}
 
// 2(Encryption)에서 변환되는지 테스트
if (!Enum.TryParse("2"out type&& type == EnumType.Encryption)
{
    throw new InvalidCastException("LdapAuthenticationType값이 올바르지 않습니다. 다시 확인하여 주시기 바랍니다.");
}
 
// ServerBind 변환되는지 테스트
if (!Enum.TryParse("ServerBind"out type&& type == EnumType.ServerBind)
{
    throw new InvalidCastException("LdapAuthenticationType값이 올바르지 않습니다. 다시 확인하여 주시기 바랍니다.");
}
 
// 512(ServerBind)에서 변환되는지 테스트
if (!Enum.TryParse("512"out type&& type == EnumType.ServerBind)
{
    throw new InvalidCastException("LdapAuthenticationType값이 올바르지 않습니다. 다시 확인하여 주시기 바랍니다.");
}

[코드1] 형변환 테스트 코드



 위 코드는 형변환이 제대로 되는지 테스트하는 코드며 원하는 타입으로 변환이 되지 않았을 때는 예외가 발생하도록 하였다.


public enum EnumType
{
    None = 0,
    Secure = 1,
    Encryption = 2,
    SecureSocketsLayer = 2,
    ReadonlyServer = 4,
    Anonymous = 16,
    FastBind = 32,
    Signing = 64,
    Sealing = 128,
    Delegation = 256,
    ServerBind = 512,
}

[코드2] Enum 선언





[Code Snippet]




+ Recent posts