在C#中铸造出范围的一个数一个枚举不会产生异常 [英] Casting an out-of-range number to an enum in C# does not produce an exception
本文介绍了在C#中铸造出范围的一个数一个枚举不会产生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码不会产生异常,而是传递值4至尖沙咀。谁能解释这背后的原因是什么?
公共枚举测试
{
A = 1,
B = 2,
C = 3
}
测试TST =(测试)(4)
解决方案
在C#,Java不同,枚举不检查。你可以有基础类型的任何值。这就是为什么检查您输入这是非常重要的。
如果(!Enum.IsDefined(typeof运算(MyEnum),值))
抛出新ArgumentOutOfRangeException();
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);
解决方案
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.
if(!Enum.IsDefined(typeof(MyEnum), value))
throw new ArgumentOutOfRangeException();
这篇关于在C#中铸造出范围的一个数一个枚举不会产生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文