-
Convert a string to an enum in C#닷넷/C# 2022. 5. 10. 14:57반응형
Enum.TryParse("Active", out StatusEnum myStatus);
This also includes C#7's new inline out variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the myStatus variable.
If you have access to C#7 and the latest .NET this is the best way.
Original Answer
In .NET it's rather ugly (until 4 or above):
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
I tend to simplify this with:
public static T ParseEnum<T>(string value) { return (T) Enum.Parse(typeof(T), value, true); }
Then I can do:
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
One option suggested in the comments is to add an extension, which is simple enough:
public static T ToEnum<T>(this string value) { return (T) Enum.Parse(typeof(T), value, true); } StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
Finally, you may want to have a default enum to use if the string cannot be parsed:
public static T ToEnum<T>(this string value, T defaultValue) { if (string.IsNullOrEmpty(value)) { return defaultValue; } T result; return Enum.TryParse<T>(value, true, out result) ? result : defaultValue; }
Which makes this the call:
StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
However, I would be careful adding an extension method like this to string as (without namespace control) it will appear on all instances of string whether they hold an enum or not (so 1234.ToString().ToEnum(StatusEnum.None) would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.
[출처: https://stackoverflow.com/questions/16100/convert-a-string-to-an-enum-in-c-sharp]
반응형'닷넷 > C#' 카테고리의 다른 글
C# 계산오류? 부동 소수점에 대해 알아보자 (0) 2023.03.02 C# URL 파라미터 인코딩 방법 (특수문자가 있는 경우에 사용) (0) 2022.10.19 c# 부팅시 자동 시작하는 프로그램, 레지스트리에 등록 또는 삭제 방법 (0) 2021.11.30 C# LINQ multiple select (0) 2021.11.11 C# 두 위도와 경도 좌표 사이의 거리를 계산 하는 방법 (0) 2021.07.19