解决此问题的几种不同方法:
只需将Environment.Exit替换为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;
}
}
初始化队列为空,这其实只是一个编译器把戏,说:“我会找出我自己未初始化的变量,非常感谢你。”这是一个很有用的技巧,但在这种情况下我不喜欢它 - 如果分支太多,很容易检查你是否正确地做了这件事。如果你真的想做这种方式,这样的事情会更清楚:
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());
}
添加return语句Environment.Exit后。再次,这更是一个编译器的伎俩 - 但稍微合法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());
}
我不能给你任何指示,但我希望你能处理这一个。 – wprl 2008-11-01 20:40:31