我正在研究一些代码示例,并且看到了以下示例的类似变化,其中一个让我非常好奇。
当goto_tag
放在try
声明之前。这完全有道理,它再次穿过try
。
retry_tag: //the goto tag to re-attempt to copy a file
try {
fileInfo.CopyTo( toAbsolutePath + fileInfo.Name, true ); //THIS LINE MIGHT FAIL IF BUSY
} catch {
Thread.Sleep(500); //wait a little time for file to become available.
goto retry_tag; //go back and re-attempt to copy
}
但是,随着以下内容呈现给我,我不明白。当goto_tag
被放置在try
语句中时,从catch
块中调用。
try {
retry_tag: //the goto tag to re-attempt to copy a file
fileInfo.CopyTo( toAbsolutePath + fileInfo.Name, true ); //THIS LINE MIGHT FAIL IF BUSY
} catch {
Thread.Sleep(500); //wait a little time for file to become available.
goto retry_tag; //go back and re-attempt to copy
}
try
块复活了吗?或者这两个例子在功能上是否相同,或者这是一个完全非法的操作,甚至不会编译?
这完全出于好奇,当然我更喜欢第一个例子,如果他们中的任何一个......
感谢您的任何见解!!
要真正回答你的问题:
不,这些都不一样。
第一个例子将编译;第二个是非法的。
(你是否应该编写这样的代码是一个不同的问题......当然,如果你能帮助它,你就不应该这样做。)
你可以实现一个简单的while
而不是goto
:
// loop until ...
while (true) {
try {
fileInfo.CopyTo(Path.Combine(toAbsolutePath, fileInfo.Name), true);
// ... file copied
break;
}
catch (IOException) {
Thread.Sleep(500); //wait a little time for file to become available.
}
}