为什么我可以将无效值解析为 .NET 中的 Enum?
为什么这可能?这是一个错误吗?
using System;
public class InvalidEnumParse
{
public enum Number
{
One,
Two,
Three,
Four
}
public static void Main()
{
string input = "761";
Number number = (Number)Enum.Parse(typeof(Number), input);
Console.WriteLine(number); //outputs 761
}
}
Why is this even possible? Is it a bug?
using System;
public class InvalidEnumParse
{
public enum Number
{
One,
Two,
Three,
Four
}
public static void Main()
{
string input = "761";
Number number = (Number)Enum.Parse(typeof(Number), input);
Console.WriteLine(number); //outputs 761
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是枚举在 .NET 中的工作方式。枚举不是一组限制性的值,它实际上只是一组数字名称(以及将这些名称收集在一起的类型) - 我同意这有时很痛苦。
如果要测试枚举中是否真正定义了某个值,可以使用
Enum.IsDefined
解析后。如果您想以更类型安全的方式执行此操作,您可能需要查看我的 Unconstrained Melody 项目,其中包含一堆受约束的通用方法。That's just the way enums work in .NET. The enum isn't a restrictive set of values, it's really just a set of names for numbers (and a type to collect those names together) - and I agree that's a pain sometimes.
If you want to test whether a value is really defined in the enum, you can use
Enum.IsDefined
after parsing it. If you want to do this in a more type-safe manner, you might want to look at my Unconstrained Melody project which contains a bunch of constrained generic methods.如果您有一个带有
[Flags]
属性的enum
,则可以具有任意值组合。例如:您可以这样做:
If you have a
enum
with[Flags]
attribute, you can have any value combination. For instance:You could to do this: