C# 的 C++ ifstream 异常掩码

C++ ifstream exception masks for C#

如何将此行从 C++ 转换为 C#?

std::ifstream in;
in.exceptions(std::ios_base::badbit); //*THIS LINE*

根据 this page,上一行代码为流设置了一个新的异常掩码并清除了所有当前错误状态标志。我还猜测它是上面链接页面中 std::ios::exceptions 的 "second form"。

由于我对 C# 的 FileStream class 缺乏经验,我一直很困惑,因为缺少类似的东西。

两个 FileStream.Read and FileStream.Write methods will throw an IOException 应该发生任何潜在的 I/O 错误。这是默认行为。

与 C++ 不同,异常抛出是 C# 中错误处理的预期形式。因为异常从一开始就是 .NET 的一部分,所以有 none 的 the contention 围绕流使用异常,就像在 C++ 中一样。

大多数(如果不是全部).NET 框架标准库将在异常状态下抛出异常。我能想到的唯一例外是使用 Try-Parse pattern 时,这对预期行为非常明确。