根據描述屬性擷取枚舉值
在某些程式設計場景中,需要根據枚舉關聯的描述屬性來檢索枚舉值。這在處理具有描述性標籤的枚舉時尤其有用。
可以使用 Enum.GetValueFromDescription()
方法來實現。但是,此方法並不存在於 .NET 框架中。我們可以實作一個自訂擴充方法來彌補這個不足。以下程式碼片段示範了這樣的實作:
<code class="language-csharp">public static class EnumEx { public static T GetValueFromDescription<T>(string description) where T : Enum { foreach (var field in typeof(T).GetFields()) { if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute) { if (attribute.Description == description) return (T)field.GetValue(null); } else { if (field.Name == description) return (T)field.GetValue(null); } } throw new ArgumentException("未找到。", nameof(description)); // 或者返回 default(T); } }</code>
使用方法:
<code class="language-csharp">var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");</code>
透過呼叫 GetValueFromDescription
方法,您可以擷取與指定的描述屬性對應的枚舉值。此方法迭代枚舉的字段,檢查 DescriptionAttribute
屬性,並在匹配時返回相應的值。如果找不到符合的描述,則根據實現情況拋出異常或傳回枚舉類型的預設值。
以上是如何從 C# 中的描述屬性中檢索枚舉值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!