为什么“并非所有代码路径都返回值"?使用 switch 语句和枚举?

编程入门 行业动态 更新时间:2024-10-27 14:31:43
本文介绍了为什么“并非所有代码路径都返回值"?使用 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 语句和枚举?

本文发布于:2023-11-10 01:21:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   路径   返回值   代码   switch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!