处理 switch 语句
处理以下情况的首选方法是什么:
switch (numberOfActualBytes)
{
case 1: return something1;
case 2: return something2;
case 3: return something3;
case 4: return something4;
}
我确定,由于使用的合约,numberOfActualBytes
在1-4
范围内。
我应该如何编写不会导致并非所有代码路径都返回值
错误的代码?
我怀疑我应该在此函数末尾或在默认 switch case
,但可能有更好的解决方案。
What's the preferred way to handle the following case:
switch (numberOfActualBytes)
{
case 1: return something1;
case 2: return something2;
case 3: return something3;
case 4: return something4;
}
I know for certain that numberOfActualBytes
due to the used contract is in range 1-4
.
How should I write the code that doesn't result in not all code paths return a value
error?
I suspect I should throw some exception at the end of this function or in default switch case
, but probably there is a better solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果应用程序可以支持 1..4 合约,我更愿意在默认情况下抛出超出范围的异常。该异常反映了对调用者的期望,即他们将为我提供良好的数据。
如果您的编译器无法确定
default
情况可以解决并非所有代码路径,则将return
放在switch.但 C# 编译器会正确处理。
I prefer to throw an out-of-range exception in the
default
case if the application can be expected to uphold the 1..4 contract. The exception reflects the expectation on the caller that they will give me good data.If your compiler cannot figure out that the
default
case solves the not all code paths, then put thereturn
after theswitch
. But the c# compiler will get it right.default: return error_code
将是我的解决方案。default: return error_code
would be my solution.我可能会做这样的事情。
这不也能起到同样的作用吗?
I would probably do something like this.
Wouldn't this do the same?