gpt4 book ai didi

c# - 为什么重置 StreamReader 不允许重新读取 UTF8 中的字符串?

转载 作者:行者123 更新时间:2023-11-30 15:26:42 36 4
gpt4 key购买 nike

重置 StreamReader 会导致奇怪的行为。第一个断言成功而第二个断言失败。要纠正它,一个(坏的)解决方案包括重置到位置 3 而不是 0:sr.BaseStream.Position = 3;

using (var sr = new StreamReader(@"c:\temp\test.txt", Encoding.UTF8)) // test.txt is encoded in UTF8
{
var read = sr.ReadLine();
Assert.AreEqual("fromfile", read); // ok
sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
read = sr.ReadLine();
Assert.AreEqual("fromfile", read); //fails
}

最佳答案

您只是没能真正重置对象。在名为 _checkPreamble 的类中有一个私有(private)字段。它将被设置为 false 因为它已经被检查过。你可以破解它:

using System.Reflection;
...
var fi = typeof(StreamReader).GetField("_checkPreamble", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(sr, true);
read = sr.ReadLine();
Assert.AreEqual("fromfile", read); // okay now

当然你不会真的想写这样的代码。解决方案非常简单,只需创建一个新的 StreamReader 对象。

关于c# - 为什么重置 StreamReader 不允许重新读取 UTF8 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28857705/

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