在 C# 中,枚举上的开关是否需要默认情况?
我看过与 C++ 相关的帖子,但我特别要求 C# .NET (4.0+)。
在下面的例子中是否需要默认情况?
public enum MyEnum : int
{
First,
Second
}
public class MyClass
{
public void MyMethod(MyEnum myEnum)
{
switch (myEnum)
{
case MyEnum.First: /* ... */ break;
case MyEnum.Second: /* ... */ break;
default: /* IS THIS NECESSARY??? */ break;
}
}
}
I've seen posts relating to C++, but am asking specifically for C# .NET (4.0+).
In the following example is a default case necessary?
public enum MyEnum : int
{
First,
Second
}
public class MyClass
{
public void MyMethod(MyEnum myEnum)
{
switch (myEnum)
{
case MyEnum.First: /* ... */ break;
case MyEnum.Second: /* ... */ break;
default: /* IS THIS NECESSARY??? */ break;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个常见的误解,认为 .Net 枚举值仅限于枚举中声明的值。实际上,它们可以是枚举基本类型范围内的任何值(默认为
int
)。例如,以下代码是完全合法的。此代码将在没有警告的情况下编译,并且不会命中任何
case
标签。现在,您的代码是否选择处理这种类型的场景是一个策略决定。这不是必要,但我当然推荐拥有一个。我更喜欢为我专门为此场景编写的枚举上的每个
switch
添加一个default
,使用以下模式It's a common misconception that .Net enum values are limited to the ones declared in the Enum. In reality though they can be any value in the range of the base type of the enum (
int
by default). For example the following is perfectly legalThis code will compile without warnings and hit none of your
case
labels.Now whether your code chooses to handle this type of scenario is a policy decision. It's not necessary but I'd certainly recomend having one. I prefer to add a
default
to everyswitch
on enum I write specifically for this scenario with the following pattern这并不是绝对必要的,但有人可能会传入枚举未涵盖的值(因为枚举实际上并不限制允许的参数值的范围)。
我通常会添加一个默认值,如果指定的值是意外的,则
抛出
。It's not strictly necessary, but someone may pass in a value not covered by your enum (since enumerations do not actually restrict the range of permissible parameter values).
I typically add a default and
throw
if the specified value is unexpected.这在技术上不是必需的,但因为您可以轻松地将
MyEnum
的基础类型(通常为 int)的值转换为MyEnum
的实例。因此,最好添加一个带有 Debug.Assert() 的默认语句。It is not technically necessary, but because you can easily cast a value of
MyEnum
s underlying type (usually int) to an instance ofMyEnum
. Hence it is good practice to add a default statement with aDebug.Assert()
in it.这不是必需的,但很好的做法,因为稍后有人可能会引入新的枚举。例如,抛出一个异常,指示未处理“未知”枚举。
It is not required but good practise as someone might introduce a new enumeration later on. For example throw an exception that indicates that 'unknown' enumeration is not handled.
不,不需要默认情况。
No, the default case is not required.
从纯粹的代码角度来看,不需要有
default
情况。这只是您的逻辑要求的问题。From a purely code perspective, there's no requirement to have a
default
case. It's solely a matter of your logical requirements.如果您将其转换为枚举未定义的值(不会引发异常),或者向枚举添加更多值,则需要它。
Its needed if you cast into enum undefined value (will not throw an exception), also if you add more values to enum.