게임 프로그래밍/Unity

String을 Enum으로 바꿔 활용하기

스게 2021. 11. 12. 11:16
public static class ExtensionMethods
{
    public static T ToEnum<T>(this string value)
    {
        // + 변환 오류인 경우 디폴트값 리턴. (디폴트값 : 0번째 value)
        if(!System.Enum.IsDefined(typeof(T),value))
        {
            return default(T);
        }

        return (T)System.Enum.Parse(typeof(T), value, true);
    }
}

 

사용은

enum Test
{
    value1,
    value2
}

string test = "value1"
T value = value.ToString().ToEnum<T>();