要返回的值表示无效值

Hao*_*Lim 1 c#

假设您有一个返回枚举的函数:

public enum ServerStatus
{
    Down,
    Up
}

private ServerStatus GetServerStatus(int time)
{
    if (time >= 0 && time < 12)
    {
        return ServerStatus.Down;
    }
    else if (time >= 12 && time <= 23)
    {
        return ServerStatus.Up;
    }
    else
    {
        return ?? // Server status is neither Up nor Down
    } 
}
Run Code Online (Sandbox Code Playgroud)

我是不是该:

  1. 将"Neither"添加到ServerStatus
  2. 使GetServerStatus返回ServerStatus?并返回null
  3. 返回另一个bool,指示值是否有意义

mar*_*lam 13

如果这种情况在实践中永远不会发生,并且您不希望产生除"向上"和"向下"之外的其他东西,那么您应该抛出异常.

  • 可能是ArgumentOutOfRangeException; +1 (2认同)