为什么“不是所有的代码路径都返回一个值”用switch语句和枚举? [英] Why do "Not all code paths return a value" with a switch statement and an enum?

查看:137
本文介绍了为什么“不是所有的代码路径都返回一个值”用switch语句和枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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>。我不明白 switch 语句如何能够跳转到指定的情况之一。

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.

可以 enum 某种方式是 null

推荐答案

没有什么可说的, myEnum 的值将是这些值之一。

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

Don一个错误的枚举是限制性的值集。这只是一个名为的值集。例如,我可以通过以下方式调用您的方法:

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...

示例:

public int Method(MyEnum myEnum)
{
    if (!IsDefined(typeof(MyEnum), myEnum)
    {
        throw new ArgumentOutOfRangeException(...);
    }
    // Adjust as necessary, e.g. by adding 1 or whatever
    return (int) myEnum; 
}

假设<$ c $中的基础值之间存在明显的 关系c> MyEnum 和您要返回的值。

This assumes there's an obvious relationship between the underlying values in MyEnum and the value you want to return.

这篇关于为什么“不是所有的代码路径都返回一个值”用switch语句和枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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