代码之家  ›  专栏  ›  技术社区  ›  anthony

“file.open()”和“new filestream()”之间的差异

  •  20
  • anthony  · 技术社区  · 16 年前

    有什么区别吗?

    3 回复  |  直到 8 年前
        1
  •  24
  •   Reed Copsey    16 年前

    一个也没有。

    file.open在内部只不过是:

    public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
    {
        return new FileStream(path, mode, access, share);
    }
    

    如果不使用指定fileaccess和fileshare的重载,它将为您指定此重载(使用fileshare.none和fileaccess.write-on-append或readwrite)。

    也就是说,这是一个实现细节,而不是 documentation . 从技术上讲,未来的.NET框架版本 能够 使用不同的实现,尽管我觉得不太可能。

        2
  •  20
  •   Hans Passant    8 年前

    这种重复在.NET框架中非常少见。但有一个关于这个的故事,由科瓦利纳在 this lecture . 他们对该框架的早期版本进行了可用性研究,要求一群经验丰富的程序员(但不是.NET不可知论者)使用filestream和streadreader/writer类编写一些代码。

    情况不太好,他们有100%的不及格率。他们的反应是向system.io.file类添加方法,使用“最有可能落入成功之坑”的方法。

    很酷的视频btw,如果你完全了解框架看起来的原因。

    最好给出一个真实的答案:file.open()方法调用filestream构造函数,传递fileaccess和fileshare的值(如果不指定它们的话),它们很可能会做正确的事情。它是fileaccess.readwrite和fileshare.none。

        3
  •  5
  •   AxelEckenberger    16 年前

    File.Open() 是一种方便的方法。内部执行如下:

    public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
    {
        return new FileStream(path, mode, access, share);
    }