C# 将字符串转换为枚举类型 - 使用 Enum.Parse() 方法
在 C# 中,可以使用 Enum.Parse() 方法将字符串转换为枚举类型的元素。以下是一个示例代码:
using System;
public enum Colors
{
Red,
Green,
Blue
}
class Program
{
static void Main()
{
string colorString = "Green";
Colors color = (Colors)Enum.Parse(typeof(Colors), colorString);
Console.WriteLine(color); // 输出:Green
}
}
在这个示例中,我们首先定义了一个 Colors 枚举类型,其中包含了 Red、Green 和 Blue 三个元素。然后,我们使用 Enum.Parse() 方法将字符串 "Green" 转换为 Colors 类型的枚举元素。最后,我们将结果输出到控制台。
需要注意的是,Enum.Parse() 方法的第一个参数是目标枚举类型的 Type 对象,第二个参数是要转换的字符串。在转换之前,需要使用强制类型转换将结果转换为目标枚举类型。
原文地址: https://www.cveoy.top/t/topic/pQaS 著作权归作者所有。请勿转载和采集!