我在类中有一系列的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);
}
答案 0 :(得分:3)
在这种特定情况下,您不必处理您的信息流。处理后,BinaryReader将自动处理基础流。
但也许BinaryReader只是一个例子?
答案 1 :(得分:1)
在这种特殊情况下,BinaryReader负责传递的流,并在处置时正确关闭它。
如果您希望将来避免使用此类样板,以下内容可作为一个有用的示例:
private class MyReader : BinaryReader, IDisposable
{
private readonly Stream _input;
public MyReader(Stream input) : base(input)
{
_input = input;
}
void IDisposable.Dispose()
{
Dispose();
_input.Dispose();
}
}
答案 2 :(得分:0)
因为using只是try-finally块的简写,你可以这样做:
class Program
{
static void Main(string[] args)
{
using (var b = GetReader())
{
}
}
static B GetReader()
{
using (var a = new A())
{
return new B(a);
}
}
}
class A : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose A");
}
}
class B : IDisposable
{
public B(object obj)
{
}
public void Dispose()
{
Console.WriteLine("Dispose B");
}
}
在你的情况下:
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?
using(FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
return new BinaryReader(stream);
}
}