本文翻译自:Nested using statements in C#
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);
}
}
It seems a little odd to have nested using
statements. 嵌套using
语句似乎有点奇怪。
Is there a better way to do this? 有一个更好的方法吗?
#1楼
参考:https://stackoom.com/question/5zVp/在C-中嵌套使用语句
#2楼
If the objects are of the same type you can do the following 如果对象属于同一类型 ,则可以执行以下操作
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()),
expFile = new StreamReader(expectedFile.OpenRead()))
{
// ...
}
#3楼
There's nothing odd about it. 它没什么奇怪的。 using
is a shorthand way of ensuring the disposal of the object once the code block is finished. using
是一种在代码块完成后确保处理对象的简便方法。 If you have a disposable object in your outer block that the inner block needs to use, this is perfectly acceptable. 如果您的外部块中有一个一次性物体,内部块需要使用,这是完全可以接受的。
Edit: Too slow on the typing to show consolidated code example. 编辑:输入太慢以显示合并代码示例。 +1 to everyone else. +1给其他人。
#4楼
When the IDisposable
s are of the same type, you can do the following: 当IDisposable
的类型相同时,您可以执行以下操作:
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()),
expFile = new StreamReader(expectedFile.OpenRead()) {
// ...
}
The MSDN page on using
has documentation on this language feature. 在MSDN页面using
了这种语言功能的文档。
You can do the following whether or not the IDisposable
s are of the same type: 无论IDisposable
是否属于同一类型,您都可以执行以下操作:
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))
using (StreamWriter anotherFile = new StreamReader(anotherFile.OpenRead()))
{
// ...
}
#5楼
You can group multiple disposable objects in one using-statement with commas: 您可以使用逗号将多个一次性对象组合在一个using语句中:
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()),
expFile = new StreamReader(expectedFile.OpenRead()))
{
}
#6楼
The preferred way to do this is to only put an opening brace {
after the last using
statement, like this: 执行此操作的首选方法是仅在最后一个using
语句之后放置一个大括号{
,如下所示:
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))
using (StreamReader expFile = new StreamReader(expectedFile.OpenRead()))
{
///...
}