C# Enum.TryParse 解析无效数字字符串

标签 c# enums

C# .NET 4.5,Windows 10,我有以下枚举:

private enum Enums
{
    A=1, B=2, C=3
}

这个程序的行为非常奇怪:

public static void Main()
{
    Enums e;
    if (Enum.TryParse("12", out e))
    {
        Console.WriteLine("Parsed {0}", e);
    }
    else
    {
        Console.Write("Not parsed");
    }
    Console.ReadLine();
}

我希望 TryParse 方法的结果为假,但令我惊讶的是 控制台显示“Parsed 12”。 在Watch窗口中甚至显示值为“12”,并且是Enums类型!

对于我尝试过的任何数字字符串(例如“540”)都是如此,但对于包含字母的字符串(“A12”、“12A”)则不然。

我可以通过首先检查它是否是纯数字字符串来轻松克服这个问题,但为什么会这样呢? 是设计使然吗?

谢谢! 伊多

最佳答案

在内部,枚举存储为整数,所以这可能就是 TryParse 为传入的整数返回 true 的原因。

至于为什么任何整数都有效,这是设计使然。来自 MSDN (强调我的):

When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, result contains the default value of the underlying type of TEnum. Note that this value need not be a member of the TEnum enumeration. This parameter is passed uninitialized.

关于C# Enum.TryParse 解析无效数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35117265/

相关文章:

c# - Visual Studio 无法打开 cshtml 文件

c# - 无法通过嵌套类型访问外部类型的非静态成员

c# - http请求不包含.net core 2.1中createresponse的定义

c# - 如何从 System.Enum 转换为基本整数?

c++ - 在没有限定的情况下从类内的枚举解析名称

swift - 如何检查枚举是否与模式不匹配?

c# - 您可以将 SignalR 与 Visual Studio 2012 一起使用吗?

c# - 设计 .Net 框架应用程序的技巧

c# - 如何在枚举中使用不安全值?

Java 枚举类型错误