简体   繁体   English

重申在Catch子句中使用GoTo的Try语句?

[英]Reiterating a Try statement using GoTo in the Catch clause?

I am examining some code examples and have seen similar variation to the following examples, one of them made me very curious. 我正在检查一些代码示例,并看到与以下示例相似的变体,其中之一使我感到非常好奇。

When a goto_tag is placed before a try statement. goto_tag放在try语句之前。 This makes complete sense and it just runs through the try again. 这完全有意义,只需再次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
}   

However, as the following was presented to me I did not understand it. 但是,当我看到以下内容时,我不明白。 When a goto_tag is placed within the try statement, and is called from within the catch block. 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
}   

Is the try block resurrected? try块是否已复活? Or are the two examples functionally identical, or is this an completely illegal operation and won't even compile? 还是两个示例在功能上完全相同,或者这是完全非法的操作,甚至无法编译?

This is all purely out of curiosity, and of course I would prefer the first example, if either of them.. 这完全是出于好奇,当然,如果有其中一个,我当然更喜欢第一个示例。

Thanks for any insight!! 感谢您的见解!

To actually answer your question: 实际回答您的问题:

No, these are not the same. 不,这些一样。

The first example will compile; 第一个示例将进行编译; the second is illegal. 第二个是非法的。

(The matter of whether you should write code like this is a different question... and off course, you should not if you can help it.) (关于是否应该像这样编写代码的问题是另一个问题……当然,如果可以帮助,则不应这样做。)

You can implement a simple while instead of goto : 您可以实现一个简单的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.       
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM