In each case, the enumeration value needs to be retrieved based on the enumeration's associated description properties. Let's explore a general approach to achieve this.
Consider the following example where we have an extension method to get the description property of an enum:
<code>public static string GetDescription(this Enum value) { // 获取Description属性的实现 }</code>
Using this method, we can get the description by calling the following code:
<code>string myAnimal = Animal.GiantPanda.GetDescription(); // "Giant Panda"</code>
Now, let’s dive into the reverse process of converting a description attribute back to its corresponding enumeration value. For this purpose, we introduce a helper method:
<code>public static T GetValueFromDescription<T>(string description) where T : Enum { // 根据描述检索枚举值的实现 }</code>
In this method, we iterate over the fields of the enumeration type and use reflection to retrieve their DescriptionAttributes:
<code>foreach (var field in typeof(T).GetFields()) { // 检查DescriptionAttribute并与提供的描述匹配的逻辑 }</code>
We can use the field name as a fallback mechanism if no matching DescriptionAttribute is found. Finally, we cast the result to the desired enum type:
<code>return (T)field.GetValue(null);</code>
To use this method, simply specify the enumeration type and description properties:
<code>var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");</code>
The above is the detailed content of How to Convert an Enum Description Back to its Enum Value?. For more information, please follow other related articles on the PHP Chinese website!