c# - 使用 StreamWriter 构造函数和 File.CreateText 的区别

标签 c# file io streamwriter

有什么区别(CPU 使用率、MSIL 等):

StreamWriter sw = new StreamWriter("C:\test.txt");

和:

StreamWriter sw = File.CreateText("C:\test.txt");

?

最佳答案

不多...(通过 Reflector )

[SecuritySafeCritical]
public static StreamWriter CreateText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    return new StreamWriter(path, false);  // append=false is the default anyway
}

虽然我更喜欢使用 File.* 工厂方法,但它的值(value)在于我认为它们看起来比将一堆构造函数参数传递给 Stream 或 StreamWriter 更清晰并且更具可读性,因为很难记住哪些重载会执行什么操作不看定义。

此外,JIT 编译几乎肯定会内联调用,因此即使是单个额外方法调用的微小开销也可能不会产生。

关于c# - 使用 StreamWriter 构造函数和 File.CreateText 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304654/

相关文章:

c# - 在并发请求期间访问 session 值

c - 为什么 fgetc 或 fgets 忽略

linux - 如何使 FIO 重播多线程跟踪

performance - 压缩以提高硬盘写入性能

java - 如何将文件从SpringBoot项目资源内的子文件夹复制到资源内的另一个子文件夹

arrays - 读取具有不同行数的多个文件

c# - 如何在 LINQ to Entities 中执行 SQL "Where Exists"?

c# - 我如何使用 xUnit Assert.RaisesAny?

C#6.0 字符串插值本地化

c - 在C下的Linux ubuntu中以类似 "Jun 19 10:08"的格式打印文件的详细信息