In the C#, the string is converted into enumeration
Pay an enumeration from the string
When processing the HTML Select tag with enumeration value, you need to convert the selected string value to the corresponding enumeration value. In C#, the preferred conversion method is
. Enum.TryParse
Enum.TryParse("Active", out StatusEnum myStatus);
Copy after login
For .NET CORE and .NET Framework 4.0, it required longer grammar:
StatusEnum myStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active", true);
Copy after login
Customized enumeration analysis expansion method
For the sake of convenience, you can create a custom extension method to simplify the analysis process, such as:
public static T ParseEnum<T>(string value) => (T)Enum.Parse(typeof(T), value, true);
Copy after login
This extension method allows you to write:
StatusEnum myStatus = ParseEnum<StatusEnum>("Active");
Copy after login
Processing invalid enumeration value
In order to process the string value is not an effective enumeration value, you can add silent recognition to the
method: ParseEnum
public static T ToEnum<T>(string value, T defaultValue)
{
if (string.IsNullOrEmpty(value)) return defaultValue;
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
Copy after login
This allows you to use the following syntax:
The above is the detailed content of How to Convert a String to an Enum in C#?. For more information, please follow other related articles on the PHP Chinese website!