C#Enum.TryParse解析无效的数字字符串 [英] C# Enum.TryParse parses invalid number strings

查看:130
本文介绍了C#Enum.TryParse解析无效的数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

C# .NET 4.5, Windows 10, I have the following enum:

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

程序以非常奇怪的方式行为:

And this program behaves in a very strange way:

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方法的结果是假的,但对我来说惊喜
控制台显示解析12。
在Watch窗口中,它甚至显示的值为12,它是枚举类型!

I would expect the result of the TryParse method to be false, but to my surprise the console shows "Parsed 12". In the Watch window it even shows that the value is "12" and it is of the Enums type!

这是真的任何数字字符串,我尝试(例如540),但不适用于包含字母(A12,12A)的字符串。

This is true for any number string that I tried (e.g. "540"), but not for strings that include letters ("A12", "12A").

我可以轻松克服这一点,首先检查它是否一个数字的字符串,但为什么是这样的行为?
是按设计吗?

I can easily overcome this by first checking if it's a number-only string, but why is this the behaviour? Is it by design?

谢谢!
Ido

Thanks! Ido

推荐答案

在内部,枚举存储为整数,这很可能为什么TryParse为传递的整数返回true

Internally, enums are stored as integers so that's likely why TryParse is returning true for integers being passed in.

关于为什么整数正在工作,这是按设计。从 MSDN (强调我的):

Regarding why any integer is working, it's by design. From MSDN (emphasis mine):


当此方法返回时,结果包含一个类型为TEnum
的对象,如果解析操作成功,其值由值表示。
如果解析操作失败,结果包含
底层类型的默认值TEnum。 请注意,此值不需要是TEnum枚举
的成员。此参数未初始化。

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解析无效的数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆