解决问题的几种不同方法:
只需将 Environment.Exit 替换为 return。编译器知道 return 结束了方法,但不知道 Environment.Exit 会结束。
static void Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return;
} else {
return;
}
当然,你真的只能侥幸逃脱,因为在所有情况下你都使用 0 作为退出代码。确实,您应该返回一个 int 而不是使用 Environment.Exit。对于这种特殊情况,这将是我的首选方法
static int Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return 1;
} else {
return 2;
}
}
将队列初始化为 null,这实际上只是一个编译器技巧,上面写着“我会找出我自己的未初始化变量,非常感谢”。这是一个有用的技巧,但在这种情况下我不喜欢它 - 你有太多的 if 分支来轻松检查你是否正确地执行它。如果你真的想这样做,这样的事情会更清楚:
static void Main(string[] args) {
Byte maxSize;
Queue queue = null;
if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
Environment.Exit(0);
}
queue = new Queue(){MaxSize = maxSize};
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}
在 Environment.Exit 之后添加一个 return 语句。同样,这更像是一个编译器技巧 - 但在 IMO 中稍微合法一些,因为它也为人类添加了语义(尽管它会让你远离那个自吹自擂的 100% 代码覆盖率)
static void Main(String[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize)) {
queue = new Queue(){MaxSize = maxSize};
} else {
Environment.Exit(0);
return;
}
} else {
Environment.Exit(0);
return;
}
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}