Home >Backend Development >C++ >How to Parse a String into an Enum in C#?
In C#, the string is parsed as enumerated
General parsing method (.NET CORE and .NET Framework 4.0)
<code class="language-csharp">bool statusSuccess = Enum.TryParse("Active", out StatusEnum myStatus);</code>Simplified analysis method
<code class="language-csharp">public static T ParseEnum<T>(string value) { return (T)Enum.Parse(typeof(T), value, true); } StatusEnum myStatus = EnumUtil.ParseEnum<StatusEnum>("Active"); // 或 StatusEnum myStatus = "Active".ToEnum<StatusEnum>();</code>The method with the default value
<code class="language-csharp">public static T ToEnum<T>(this string value, T defaultValue) { if (value == null || value == "") return defaultValue; T result; return Enum.TryParse<T>(value, true, out result) ? result : defaultValue; } StatusEnum myStatus = "Active".ToEnum(StatusEnum.None);</code>Remember that when modifying core classes like string classes, use the expansion method carefully because it will affect all instances of this class, regardless of its context.
The above is the detailed content of How to Parse a String into an Enum in C#?. For more information, please follow other related articles on the PHP Chinese website!