IDisposable对象的问题
代码如下:
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
bw.Write(true);
}
ms.WriteByte((byte)1); // 此行出错: System.ObjectDisposedException
ms.Close();
}
如何让bw在回收的时候不释放ms?
------解决方案--------------------没办法,ms和bw其实是同1个
using (MemoryStream ms = new MemoryStream())
{
BinaryWriter bw = new BinaryWriter(ms)
bw.Write(true);
ms.WriteByte((byte)1);
ms.Flush();
}
------解决方案--------------------把内层的using去掉,using{}内会自动释放托管资源
------解决方案--------------------GC.KEEPALIVE(bw)