使用语句和流
我真的很困惑下面发生的事情。如果我只是尝试返回在 using 语句中创建的 MemoryStream,它将不起作用。但是,如果我调用 ToArray 并创建另一个流,效果会很好。我也尝试从 using 语句中取出第一个 MemoryStream,但结果是相同的。
using (MemoryStream memoryStream = new MemoryStream())
{
using (StreamWriter streamWriter = new StreamWriter(memoryStream))
{
using (JsonWriter jsonWriter = new JsonTextWriter(streamWriter))
{
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.Converters.Add(new JavaScriptDateTimeConverter());
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
jsonSerializer.PreserveReferencesHandling = PreserveReferencesHandling.None;
jsonSerializer.Serialize(jsonWriter, account);
streamWriter.Flush();
}
}
// Works
return new MemoryStream(memoryStream.ToArray());
// Doesn't work
return memoryStream;
}
I'm really confused as to what's going on below. If I just try and return the MemoryStream that is created in the using statement it doesn't work. However, if I call ToArray and create another stream it works great. I have alo tried taking the first MemoryStream out of the using statement but the result is the same.
using (MemoryStream memoryStream = new MemoryStream())
{
using (StreamWriter streamWriter = new StreamWriter(memoryStream))
{
using (JsonWriter jsonWriter = new JsonTextWriter(streamWriter))
{
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.Converters.Add(new JavaScriptDateTimeConverter());
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
jsonSerializer.PreserveReferencesHandling = PreserveReferencesHandling.None;
jsonSerializer.Serialize(jsonWriter, account);
streamWriter.Flush();
}
}
// Works
return new MemoryStream(memoryStream.ToArray());
// Doesn't work
return memoryStream;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
using
处理流。using
disposes the stream.“using”在关闭时会执行隐式的 .Dispose() 操作,因此我希望它不会与您想要的效果很好地配合。
我希望不使用内存流的“使用”确实会起作用,好奇为什么这对你不起作用。
"using" does an implicit .Dispose() when it closes, so I'd expect that to not play well with what you're trying to.
I would expect that not using the "using" for the memoryStream would indeed work, curious why that didn't work for you.