gpt4 book ai didi

c# - File.CreateText/File.AppendText 与 File.AppendAllText

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:40 26 4
gpt4 key购买 nike

为了使用 File.CreateText()File.AppendText() 你必须:

  1. 通过调用这些方法之一打开流
  2. 写消息
  3. 关闭流
  4. 处理流

为了使用 File.AppendAllText() 你只需使用它,它也会如果文件尚不存在,则创建该文件。

我说的是 .Net 3.5

当时有没有理由像上面第一种方法那样做?

最佳答案

当我们查看 implementation File.AppendAllText 我们发现它是一个快捷方式,实现如下:

using (StreamWriter sw = new StreamWriter(path, true, encoding))
sw.Write(contents);

其他方法打开一个流并返回它,由调用者写入、传递它等。

总是很难询问这样一个设计决定背后的原因。在这种情况下,它似乎很明显:“All”中缀表明调用者将有一个应该立即写入的完整字符串,并且不需要保持流打开 - 它是为了方便而添加的,因为这是一个常见用例。

为了支持这一点,我从 Petzold 中找到了这句话:

However, in .NET 2.0 some additional static methods were added to the File class that make a whole lot of sense. These methods let you open, read from (or write to), and close a file, all in one statement.

完全删除以前的方法以支持简化的方法意味着灵 active 的损失 - 开发人员仍然会遇到需要使用流的情况。

关于c# - File.CreateText/File.AppendText 与 File.AppendAllText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com