The best practice of the string to the enumeration conversion in the enumeration
In C# development, converting string to enumeration value is a common task. This article will explore the most effective way to achieve this conversion.
Found TryParse method
Starting from .NET CORE and .NET Framework ≥4.0, you can use the genealist method to resolve enumeration:
This method not only tries to resolve the string as enumeration value, but also converts it to an explicit enumeration type, and assigns it to MyStatus variable.
<code class="language-csharp">Enum.TryParse("Active", out StatusEnum myStatus);</code>
For the older version of the .NET Framework, the custom expansion method can simplify the analysis process:
How to use:or, you can use the toenum extension method:
<code class="language-csharp">public static T ParseEnum<T>(string value) { return (T)Enum.Parse(typeof(T), value, true); }</code>
Processing the default value
<code class="language-csharp">StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");</code>
In order to specify the default enumeration value when the conversion fails, you can use the expansion method with the default parameter:
<code class="language-csharp">public static T ToEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value, true); } StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();</code>
How to use:
Precautions
<code class="language-csharp">public static T ToEnum<T>(this string value, T defaultValue) { if (string.IsNullOrEmpty(value)) { return defaultValue; } T result; return Enum.TryParse<T>(value, true, out result) ? result : defaultValue; }</code>
The above is the detailed content of How to Efficiently Convert Strings to Enums in C#?. For more information, please follow other related articles on the PHP Chinese website!