简体   繁体   English

空的“使用中”块

[英]Empty “using” block

It has already been determined here that an empty using block is not an appropriate way to override Dispose() , but what about the following case? 它已经确定这里是一个空的使用块不是重写适当的方式Dispose() ,但对于以下情况?

Is this a legitimate use for an empty using block? 这是空的using块的合法使用吗?

try
{
    using (File.OpenRead(sourceFile)) { }
}
catch (FileNotFoundException)
{
    error = "File not found: " + sourceFile;
}
catch (UnauthorizedAccessException)
{
    error = "Not authorized to access file: " + sourceFile;
}
catch (Exception e)
{
    error = "Error while attempting to read file: " + sourceFile + ".\n\n" + e.Message;
}

if (error != null)
    return error;

System.Diagnostics.Process.Start(sourceFile);

No it's not a legitimate use for an empty using block. 不,对于空的using块,这不是合法用途。

You can simply write the try like this: 您可以像这样简单地编写try:

try
{
    File.OpenRead(sourceFile).Close();
}

Either OpenRead() will succeed and return a stream that you must close (or dispose, but I think .Close() better expresses your intent), or it will thrown an exception and not return anything. OpenRead()将成功并返回必须关闭(或处置,但我认为.Close()更好地表达您的意图)的流,否则它将引发异常并且不返回任何内容。

Therefore you can always just close the returned value. 因此,您始终可以只关闭返回值。

(I assume that you are just checking for read access before doing something else. However, be aware that you could in theory have a race condition because the accessibility of the file could change between you making this check and later on actually opening the file. This is unlikely to happen in practice, but you should be aware of the possibility.) (我假设您只是在做其他事情之前检查了读访问权限。但是,请注意,理论上您可能会遇到竞争状况,因为在进行此检查与稍后实际打开文件之间,文件的可访问性可能会发生变化。实际上这不太可能发生,但是您应该意识到这种可能性。)

Not much sense in using empty using block, as you simply can add finally at the end of catch chains and handle Dispose there: 使用空的using块没有太大意义,因为您可以最终在catch链的末尾添加并在此处处理Dispose

FileStream fs;
try {

    fs = File.OpenRead(sourceFile); 
}
catch(..) {
}
catch(..) {
}
catch(..) {
}
finally {

  if(fs !=null) {
      fs.Close();
      fs.Dispose();

  }
}

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

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