/
deminnm
/
CsharpExamples
Обзор
Документация
Войти
/
deminnm
/
CsharpExamples
Код
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/EnumBestPractices/Program.cs
47 строк
1 KB
Nickolay Demin
feat: использование Enum с атрибутами
30 май 2026, 20:23
30 май 2026, 20:23
1f6b71c
Код
Авторство
О чём код?
using System.ComponentModel; // нужно для [Description] using System.Reflection; // нужно для GetDescription() Console.WriteLine("Enum Best Practices"); Console.WriteLine("Payment Method: " + PaymentMethod.CreditCard.GetDescription()); Console.WriteLine("Payment Method: " + PaymentMethod.DebitCard.GetDescription()); Console.WriteLine("Payment Method: " + PaymentMethod.BankTransfer.GetDescription()); Console.WriteLine("Payment Method: " + PaymentMethod.Other.GetDescription()); TryToParseAndPrint("CreditCard"); TryToParseAndPrint("ErrorMethod"); void TryToParseAndPrint(string value) { if (Enum.TryParse<PaymentMethod>(value, out PaymentMethod paymentMethod)) { Console.WriteLine("Payment Method: " + paymentMethod.GetDescription()); } else { Console.WriteLine("Payment Method: Unknown"); } } public static class EnumExtensions { public static string GetDescription(this Enum value) { return value.GetType() .GetField(value.ToString()) ?.GetCustomAttribute<DescriptionAttribute>() ?.Description ?? value.ToString(); } } enum PaymentMethod : byte { [Description("Credit Card")] CreditCard = 1, [Description("Debit Card")] DebitCard = 2, [Description("Bank Transfer")] BankTransfer = 3, Other }