解決此問題的幾種不同方法:
只需將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