其他人已经说过了,但这是因为它们来自TextReader/TextWriter,可以代替它们使用。一方面,如果您只想将内容作为字符串,则使用与用于文件的相同方法输出行更有意义。如果您想要在内存中跨越多行的输出,为什么还要记住使用 StringBuilder 在每行的末尾放置“\r\n”?如果您希望代码在仅使用“\n”作为换行符的系统上运行或格式化数据怎么办?
StringBuilder sb = new StringBuilder();
// will be invalid on systems that only use \n
sb.AppendFormat("{0:yyyy-MM-dd HH:mm:ss} - Start\r\n", DateTime.Now);
// still have to add an extra parameter
sb.AppendFormat("The current time is {0:yyyy-MM-dd HH:mm:ss}{1}", DateTime.Now,
Environment.NewLine);
StringWriter sw = new StringWriter();
// Don't have to worry about it, method name tells you there's a line break
sw.WriteLine("{0:yyyy-MM-dd HH:mm:ss} - Start", DateTime.Now);
// no extra parameters
sw.WriteLine("The current time is {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
假设您想逐行处理文件,您可能会使用 StreamReader 而不是将整个文件加载到 StringBuilder 并通过换行符将其拆分为数组,对吗?使用 StringReader,您可以通过从 TextBox 或 Web 表单中的字符串创建 StringReader 来使用完全相同的方法(只要它采用通用 TextReader)。
Linq2Sql DataContexts 有一个 Log 属性,您可以将其设置为 TextWriter,以便在执行查询之前输出查询以查看正在运行的确切内容。您可以将其设置为附加到文件的 TextWriter,但您可以将 StringWriter 附加到它并在测试时在网页底部输出内容...