Home >Backend Development >C++ >How to Safely Parse Enum Strings with a Default Value in C#?
Formation method and enumeration type constraints
The goal is to create a generic function, extending the
function, and allows the default value when you cannot find the matching value of the matching. This function should not be distinguished by the case.
Enum.Parse
However, when trying to use the following code definition function:
I will encounter an error, pointing out that the constraint cannot be a special class (System.enum).
<code class="language-csharp">public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum { // 实现... }</code>
Solution:
In order to solve this error and allow the use of generic enumerations, the constraint can be modified:
The constraint after this update ensures that T is a structure and also supports the IconVertible interface, which is implemented by enumeration.
<code class="language-csharp">public static T GetEnumFromString<T>(string value, T defaultValue) where T : struct, IConvertible</code>Improved implementation:
The following modified code demonstrates the improvement of the improvement:
This method now accepts generic enumeration types, and is completely safe, ensuring that only effective enumeration values are returned. The use ofguarantees the correctness of cross -cultural.
The above is the detailed content of How to Safely Parse Enum Strings with a Default Value in C#?. For more information, please follow other related articles on the PHP Chinese website!