小编Por*_*nut的帖子

使用Enum.Parse()时出现意外结果

class Program
{
    static void Main(string[] args)
    {
        String value = "Two";
        Type enumType = typeof(Numbers);
        Numbers number = (Numbers)Enum.Parse(enumType, value);
        Console.WriteLine(Enum.Parse(enumType, value));
    }

    public enum Numbers : int
    {
        One,
        Two,
        Three,
        Four,
        FirstValue = 1
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在应用程序中使用的枚举的简化版本.为什么某些枚举名称没有值的原因是因为我使用其名称作为参数执行Enum.Parse,而具有值的值则从int解析.

如果您单步执行上面的代码并调查'number'变量,您会看到它实际上是'Two',但控制台中的输出是'FirstValue'.此时我看不出原因,是吗?

好的,解决方案很简单 - 只需给无价值的枚举值.但我仍然很好奇.

c# enums parsing

3
推荐指数
1
解决办法
1237
查看次数

标签 统计

c# ×1

enums ×1

parsing ×1