C# 使用 Enum.Parse 将 int 值转换为枚举值
在 C# 中,可以使用 Enum.Parse 方法将 int 值转换为对应的枚举值。以下是一个示例:
enum Colors
{
Red = 1,
Green = 2,
Blue = 3
}
int colorValue = 2;
Colors color = (Colors)Enum.Parse(typeof(Colors), colorValue.ToString());
Console.WriteLine(color); // 输出:Green
在上面的示例中,我们定义了一个 Colors 枚举,其中每个枚举成员都有一个与之对应的 int 值。然后,我们使用 Enum.Parse 方法将 int 值 2 转换为对应的枚举值。最后,我们将枚举值打印到控制台上,输出为 'Green'。
原文地址: https://www.cveoy.top/t/topic/pZbu 著作权归作者所有。请勿转载和采集!