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.
Enum.TryParse("Active", out StatusEnum myStatus);
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:
public static T ParseEnum<T>(string value) { return (T)Enum.Parse(typeof(T), value, true); }
<理> Processing the default value
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
In order to specify the default enumeration value when the conversion fails, you can use the expansion method with the default parameter:
public static T ToEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value, true); } StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
How to use: <<>
<事> Precautions
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; }
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!