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/