使代码无法访问

Koc*_*vid 0 c#

标记代码无法访问的最佳方法是什么,因此编译器不会给出错误消息?一个简短的例子:

int x;
if (y == 0) x = 1;
else if (y == 1) x = 2;

Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)

我知道y可以是0或1,但C#会给出一条消息,即x不会使所有路径成为值.真正的代码不是这个,但我想让它更短.

抛出异常是一种好习惯,还是有其他方法?

int x;
if (y == 0) x = 1;
else if (y == 1) x = 2;
else throw new Exception();

Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

我会抛出一个异常 - 它表明世界不是你期望的状态,你最好在你做任何伤害之前戒掉:

if (y == 0)
{
    x = 1;
}
else if (y == 1)
{
    x = 2;
}
else
{
    throw new IllegalStateException("y should be 0 or 1");
}
Run Code Online (Sandbox Code Playgroud)

或者,对于像这样的简单情况,请使用开关/外壳:

switch (y)
{
    case 0:
        x = 1;
        break;
    case 1:
        x = 2;
        break;
    default:
        throw new IllegalStateException("y should be 0 or 1");
}
Run Code Online (Sandbox Code Playgroud)

(如注释中所述,if y是一个方法参数,那么ArgumentOutOfRangeException更合适.或者如果由于参数值y只是一个或零,那么再次指出原因.如果基本上它是一个上面是适当的关于世界整体状况的问题.)