File.Create 个查询

File.Create queries

我最近发现 this post Jon Skeet 标记的答案。 他在其中解释了创建空文件的不同方法,例如:

using (File.Create(filename)) ;

using (File.Create(filename)) {}

File.Create(filename).Dispose();

然后还有另一种人们推荐使用的方式:

File.Create(filename).Close();

现在 Jon 的回答详细介绍了使用哪一个以及为什么等。但答案是 outdated/old 并且没有像我想要的那样详细说明哪个更好用于确保文件已关闭以及原因。

答案绝对不会过时。您可以通过对公开参考文献 source codeFileStream.Dispose 方法的实际实现的一些研究来检查 FileStreamDispose 方法将执行调用handle.Dispose,并执行一些其他操作。

FileStream class 不会覆盖在其基础 class 中实现的虚拟 Stream.Close() 方法的实现。这个基础 class 目前只会调用虚拟 Dispose(true),因此导致相同的路径。

Close 方法的文档中所述:

This method calls Dispose, specifying true to release all resources. You do not have to specifically call the Close method. Instead, ensure that every Stream object is properly disposed. You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method.

尽管如此,当您使用 IDisposable 实例时,您始终应该调用 Dispose1,因为它可以(现在或将来的某个时间)保存除文件句柄之外的其他内部资源,如果您只在 FileStream实例.

话虽这么说,确保正确处理的静态文件创建方法(例如 File.WriteAllBytesFile.WriteAllText)也可以使用。但是 - 在我看来 - 这些感觉很尴尬并且不能很好地表达意图。

将其包装在名为 CreateEmptyFile 的静态方法中,或者按照原始答案中的建议使用单个方法 Create 的静态 class EmptyFile 可以明确说明什么你的意图是。

1 这应该理解为直接调用 Dispose 或(最好)将资源包装在一个 using 块。