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
Release: 2025-02-01 06:01:09
Original
957 people have browsed it

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).
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
    // 实现...
}
Copy after login

<决> 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.

public static T GetEnumFromString<T>(string value, T defaultValue) where T : struct, IConvertible
Copy after login
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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template