为什么"并非所有code路径返回一个值QUOT;与switch语句和枚举? [英] Why do "Not all code paths return a value" with a switch statement and an enum?

查看:250
本文介绍了为什么"并非所有code路径返回一个值QUOT;与switch语句和枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

public int Method(MyEnum myEnum)
{
    switch (myEnum)
    {
        case MyEnum.Value1: return 1;
        case MyEnum.Value2: return 2;
        case MyEnum.Value3: return 3;
    }
}

public enum MyEnum
{
    Value1,
    Value2,
    Value3
}

和我得到的错误:不是所有的code路径返回一个值。我不明白怎么开关语句可能永远无法跳转到指定的案例之一。

And I get the error: "Not all code paths return a value". I do not understand how that switch statement could ever not jump to one of the specified cases.

可以在枚举某种程度上是

推荐答案

还有什么可说的了 myEnum 的值将是这些值之一。

There's nothing to say that the value of myEnum will be one of those values.

请不要误会枚举,作为一个的限制的设定值。这真的只是一个的的设定值。例如,我可以打电话给你的方法:

Don't mistake enums for being a restrictive set of values. It's really just a named set of values. For example, I could call your method with:

int x = Method((MyEnum) 127);

你会希望这样做?如果你想让它抛出一个异常,你可以做,在默认情况下:

What would you want that to do? If you want it to throw an exception you can do that in a default case:

switch (myEnum)
{
    case MyEnum.Value1: return 1;
    case MyEnum.Value2: return 2;
    case MyEnum.Value3: return 3;
    default: throw new ArgumentOutOfRangeException();
}

另外,您可以使用 Enum.IsDefined 的前期,如果你想switch语句之前做一些其他工作。有拳击的缺点...有一些方法一轮,但他们通常更多的工作...

Alternatively you could use Enum.IsDefined upfront, if you want to do some other work before the switch statement. That has the disadvantage of boxing... there are some ways round that, but they're generally more work...

这篇关于为什么"并非所有code路径返回一个值QUOT;与switch语句和枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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