在 C# 中将超出范围的数字转换为枚举不会产生异常 [英] Casting an out-of-range number to an enum in C# does not produce an exception

查看:38
本文介绍了在 C# 中将超出范围的数字转换为枚举不会产生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不会产生异常,而是将值 4 传递给 tst.谁能解释这背后的原因?

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);

推荐答案

在 C# 中,与 Java 不同,不检查枚举.您可以拥有任何基础类型的值.这就是为什么检查您的输入非常重要.

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屋!

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