gpt4 book ai didi

c# - 详尽开关的编译器错误

转载 作者:太空狗 更新时间:2023-10-29 17:40:17 27 4
gpt4 key购买 nike

为什么在下面的代码中,VeryBoolToBool() 会出现“并非所有代码路径都返回一个值”?

public enum VeryBool { VeryTrue, VeryFalse };
public bool VeryBoolToBool(VeryBool veryBool)
{
switch(veryBool)
{
case VeryBool.VeryTrue:
return true;

case VeryBool.VeryFalse:
return false;

// Un-commenting the unreachable(?) default clause will solve this
// default:
// throw new HowTheHellDidIGetHereException();
}
}

编译器看不到 VeryBool 没有其他选项吗?

最佳答案

Can't the compiler see there are no other options for VeryBool?

不,因为有。例如,我可以调用:

VeryBoolToBool((VeryBool) 5);

C# 中的枚举不是有限的值集。它们是有效命名的数字,具有额外的编译时类型安全性,因为枚举之间或枚举与数字之间没有隐式转换。 (虽然有显式转换。)然而,显式转换确保所讨论的值是一个具有名称的值。

除此之外,C# 中的 switch 从不检查是否显式列出了该类型的所有可能值。除非有 default 情况(并且所有情况都终止),否则 switch 语句的末尾始终被视为“可到达”。更准确地说,来自 C# 5 规范第 8.7.2 节的末尾:

The end point of a switch statement is reachable if at least one of the following is true:

  • The switch statement contains a reachable break statement that exits the switch statement.
  • The switch statement is reachable, the switch expression is a non-constant value, and no default label is present.
  • The switch statement is reachable, the switch expression is a constant value that doesn’t match any case label, and no default label is present.

关于c# - 详尽开关的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759070/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com