Home >Backend Development >C++ >How to Safely Parse Enum Strings with a Default Value in C#?

How to Safely Parse Enum Strings with a Default Value in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-01 06:01:09914browse

How to Safely Parse Enum Strings with a Default Value in C#?

Formation method and enumeration type constraints

Problem description:

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 of

guarantees 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn