在 C# 中将超出范围的数字转换为枚举不会产生异常
以下代码不会产生异常,而是将值 4 传递给 tst。 谁能解释这背后的原因吗?
public enum testing
{
a = 1,
b = 2,
c = 3
}
testing tst = (testing)(4);
The following code does not produce an exception but instead passes the value 4 to tst. Can anyone explain the reason behind this?
public enum testing
{
a = 1,
b = 2,
c = 3
}
testing tst = (testing)(4);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
与 Java 不同,C# 中不检查枚举。 您可以拥有基础类型的任何值。 这就是为什么检查您的输入非常重要。
In C#, unlike Java, enums are not checked. You can have any value of the underlying type. This is why it's pretty important to check your input.
由于您的枚举基于 int,因此它可以接受 int 可以接受的任何值。 由于您明确地(通过强制转换)告诉编译器可以将 4 强制转换为枚举,因此它会这样做。
Since your enum is based on int, it can accept any value that int can. And since you are telling the compiler explicitly (by casting) that it is ok to cast 4 into your enum it does so.
每个枚举都有一个用于表示的基础数字类型(例如 int)。 即使值没有名称,枚举也可能具有该值。
Each enum has an underlying numeric type (e.g. int) that is used for representation. Even if a value doesn't have a name, it's a possible value the enum can have.
其他人没有说的:通过强制转换,您可以告诉编译器您知道自己在做什么。 因此,如果您告诉它,将其视为枚举值,它就会这样做。 其他发帖者指出了为什么这仍然是允许的,因为 C# 编译器不允许很多不好的事情,即使你说你知道你在做什么。
如果不允许该值,那将非常糟糕,因为这样您就无法将标志值保存为 int。 或者,有人必须检查 int 是否是允许的组合之一,如果您使用标志枚举(具有可以或在一起的值),这可能会很多。
What others didn't say: With casting, you tell the compiler that you know what you're doing. So if you tell it, treat this as an enum value, it does. The other posters pointed out why this is still allowed, as the C# compiler doesn't allow many bad things, even if you say you know what you're doing.
It would be really bad if the value was not allowed, because then you couldn't save a flag value as an int. Or, someone had to check whether the int is one of the allowed combinations, which can be a lot if you use a flag enum (with values that can be or'ed together).