我有以下代码:
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
语句怎么可能永远不会跳转到指定的情况之一。
enum
能否以某种方式成为null
?
最佳答案
毫无疑问 myEnum
的值将是这些值之一。
不要将枚举误认为是一组限制值。它实际上只是一组命名值。例如,我可以调用您的方法:
int x = Method((MyEnum) 127);
你希望它做什么?如果你想让它抛出异常,你可以在默认情况下这样做:
switch (myEnum)
{
case MyEnum.Value1: return 1;
case MyEnum.Value2: return 2;
case MyEnum.Value3: return 3;
default: throw new ArgumentOutOfRangeException();
}
或者,如果您想在 switch 语句之前做一些其他工作,您可以预先使用 Enum.IsDefined
。这有拳击的缺点……有一些方法可以解决这个问题,但它们通常需要更多的工作……
示例:
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
中的基础值与您要返回的值之间存在明显关系。
关于c# - 为什么 "Not all code paths return a value"带有 switch 语句和枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2071345/