-
[C#] Enum, enumC#/기초 2025. 7. 10. 12:24
https://learn.microsoft.com/ko-kr/dotnet/api/system.enum.getnames?view=net-9.0
Enum.GetNames 메서드 (System)
지정된 열거형에서 상수 이름의 배열을 검색합니다.
learn.microsoft.com
Enum value 이름들 가져오기
Enum.GetNames(typeof(InternalRuleCommand));

Enum 이름 가져오기
case nameof(SomeEnum.SomeValue):

Get Enum Description
public static class EnumHelper { public static string Description(this Enum value) { var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Any()) return (attributes.First() as DescriptionAttribute).Description; // If no description is found, the least we can do is replace underscores with spaces // You can add your own custom default formatting logic here TextInfo ti = CultureInfo.CurrentCulture.TextInfo; return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " "))); } public static IEnumerable<ValueDescription> GetAllValuesAndDescriptions(Type t) { if (!t.IsEnum) throw new ArgumentException($"{nameof(t)} must be an enum type"); return Enum.GetValues(t).Cast<Enum>().Select((e) => new ValueDescription() { Value = e, Description = e.Description() }).ToList(); } }
enum Description으로 value 가져오기
public static class EnumExtensions { public static T GetValueFromDescription<T>(string description) where T : Enum { foreach (var field in typeof(T).GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute != null) { if (attribute.Description == description) return (T)field.GetValue(null); } else { if (field.Name == description) return (T)field.GetValue(null); } } throw new ArgumentException("Not found.", nameof(description)); } }Use
728x90'C# > 기초' 카테고리의 다른 글
[C#][별**] Task.Run (0) 2025.09.04 [C#] 기본 문자열 서식 ( tab, backspace, etc) (0) 2025.08.20 [C#] paragma warning (0) 2025.07.04 [C#] IAsyncEnumerable (0) 2025.07.04 [C#] String ! 널 연산자 방어 (1) 2025.07.03 댓글