在 C# 中顯示具有人類可讀字串的枚舉
枚舉對於表示命名常數很有價值,但直接顯示它們的值通常對使用者來說缺乏清晰度。本指南示範如何將枚舉值對應到使用者友善的字串,而不需要反向字串到值的轉換。
此解決方案利用了 Description
中的 System.ComponentModel
屬性。 透過將此屬性套用至枚舉成員,您可以為每個值提供更具描述性的標籤。
範例:
<code class="language-csharp">private enum PublishStatusValue { [Description("Not Completed")] NotCompleted, Completed, Error }</code>
擷取使用者友善的字串:
以下擴充方法檢索描述或枚舉的預設字串表示(如果未找到描述):
<code class="language-csharp">public static string GetDescription<T>(this T enumerationValue) where T : struct { Type type = enumerationValue.GetType(); if (!type.IsEnum) { throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue"); } MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString()); if (memberInfo != null && memberInfo.Length > 0) { object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return ((DescriptionAttribute)attrs[0]).Description; } } return enumerationValue.ToString(); }</code>
此方法有效地提供了使用者友善的輸出,增強了程式碼可讀性和使用者體驗。
以上是如何從 C# 中的枚舉中獲取用戶友好的字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!