c# - 为什么 "Not all code paths return a value"带有 switch 语句和枚举?

标签 c# .net visual-studio-2008 c#-3.0 enums

我有以下代码:

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/

相关文章:

如果属性在 List<string> 中,C# 从 List<T> 中删除所有项目

c# - 检查 WebBrowser 是否已加载

c++ - 在 Visual Studio 2008 Pro 和 Standard 版本中编译项目有区别吗?

c++ - 将内部版本号/内部版本 ID 嵌入到 Visual Studio 2008 中的项目中

c++ - 使用boost math的编译问题

c# - 适用于 Windows Mobile 的 gzip 工具比 SharpZipLib 更好?

c# - 在 FormFlows - Bot Framework 中为 Quit 添加另一个关键字

c# - 哪个字符串连接操作更快 - "+"或 string.Concat

.net - .NET 中队列 <T> 的大小限制?

.net - 对于使用 CQRS 的 ASP.NET MVC 应用程序来说,什么是好的读取模型?