在 C# 中嵌套 using 语句 [英] Nested using statements in C#

查看:37
本文介绍了在 C# 中嵌套 using 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目.我必须比较两个文件的内容,看看它们是否精确匹配.

I am working on a project. I have to compare the contents of two files and see if they match each other precisely.

在大量的错误检查和验证之前,我的初稿是:

Before a lot of error-checking and validation, my first draft is:

  DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory + "\TestArea\");
  FileInfo[] files = di.GetFiles(filename + ".*");

  FileInfo outputFile = files.Where(f => f.Extension == ".out").Single<FileInfo>();
  FileInfo expectedFile = files.Where(f => f.Extension == ".exp").Single <FileInfo>();

  using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))
  {
    using (StreamReader expFile = new StreamReader(expectedFile.OpenRead()))
    {
      while (!(outFile.EndOfStream || expFile.EndOfStream))
      {
        if (outFile.ReadLine() != expFile.ReadLine())
        {
          return false;
        }
      }
      return (outFile.EndOfStream && expFile.EndOfStream);
    }
  }

嵌套 using 语句似乎有点奇怪.

It seems a little odd to have nested using statements.

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

最好的方法是只在最后一个 using 语句之后放置一个左大括号 {,像这样:

The preferred way to do this is to only put an opening brace { after the last using statement, like this:

using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))
using (StreamReader expFile = new StreamReader(expectedFile.OpenRead())) 
{
    ///...
}

这篇关于在 C# 中嵌套 using 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆