自动处置在函数调用中创建的对象
我在一个类中有一系列 Read() 重载。 每个文件都只打开足够长的时间来读取,所以我有:
public void Read(blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some stuff
}
}
public void Read(blah blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some different stuff
}
}
有没有什么方法可以将流和读取器创建包装在函数中,但仍然保留 using() 来自动处理所有内容? 例如
public void Read(blah)
{
using (var reader = GetReader())
{
//read some stuff
}
}
public void Read(blah blah)
{
using (var reader = GetReader())
{
//read some different stuff
}
}
private BinaryReader GetReader()
{
//How do I dispose this stream?
FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
return new BinaryReader(stream);
}
I have a series of Read() overloads in a class.
Each opens the file only long enough to read, so I have:
public void Read(blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some stuff
}
}
public void Read(blah blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some different stuff
}
}
Is there any way of wrapping the stream and reader creation in a function, and yet still retain the using() to dispose everything automatically?
eg
public void Read(blah)
{
using (var reader = GetReader())
{
//read some stuff
}
}
public void Read(blah blah)
{
using (var reader = GetReader())
{
//read some different stuff
}
}
private BinaryReader GetReader()
{
//How do I dispose this stream?
FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
return new BinaryReader(stream);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种特定情况下,您不必处置流。处置后,BinaryReader 将自动处置底层流。
但也许 BinaryReader 只是一个例子?
In this specific case, you don't have to dispose your stream. Upon disposal, the BinaryReader will automatically dispose the underlying stream.
But maybe the BinaryReader is just an example?
在这种特殊情况下,BinaryReader 负责传递的流,并在处理时正确关闭它。
但是,如果您希望将来避免出现此类样板,以下示例可能会作为有用的示例:
In this particular case, BinaryReader is responsible for the passed stream and will Close it properly on disposal.
If however you wish to avoid such boilerplate in the future, the following may serve as a useful example:
因为 using 只是 try-finally 块的简写,所以您可以执行以下操作:
在您的情况下:
Because using is just a shorthand for try-finally block, you can do something like:
In your case: