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

查看:21
本文介绍了为什么“并非所有代码路径都返回值"?使用 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
}

我收到错误消息:并非所有代码路径都返回一个值".我不明白该 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 吗?

Can an enum somehow be null?

推荐答案

没有什么可以说 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();
}

或者,如果您想在 switch 语句之前做一些其他工作,您可以预先使用 Enum.IsDefined.这有拳击的缺点......有一些方法可以解决这个问题,但它们通常更多的工作......

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

这假设 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天全站免登陆