gpt4 book ai didi

c# - 构造函数链中的 IDisposable

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:55 26 4
gpt4 key购买 nike

我有以下两个构造函数:

public Source(FileStream fileStream) {
// Stuff
}

public Source(String fileName) : this(new FileStream(fileName, FileMode.Open)) {
// Nothing, the other constructor does the work
}

第二个构造函数的问题很明显,正在创建和使用 FileStream,但没有释放。因为它在构造函数链中,所以 using block 是不可能的。我无法将 new FileStream() 移动到构造函数的主体中,因为虽然它会在 using block 中,但另一个构造函数的逻辑不会无法被调用。我无法提取该逻辑,因为它修改了 readonly 字段。我可以在每个构造函数中复制逻辑,但这显然不是一个好的解决方案。

我真的更愿意保留第二个构造函数提供的语法糖。我怎样才能最好地做到这一点?或者这只是个坏主意?

最佳答案

看一下 StreamReader 实现,它有两种类型的 ctors:

public StreamReader(Stream stream)
: this(stream, true)
{
}

public StreamReader(string path)
: this(path, true)
{
}

在内部它们都使用参数 leaveOpen 调用相同的 Init 方法,对于第一个 ctor 和 设置为 true >false 对于第二个 ctor 并且基于此参数 Stream 得到(或不)处置。

所以你可以这样做:

public class Source : IDisposable
{
private readonly Stream _stream;
private readonly bool _leaveOpen;

private Source(Stream stream, bool leaveOpen)
{
_stream = stream;
_leaveOpen = leaveOpen;
}

public Source(FileStream fileStream) : this(fileStream, true)
{

}

public Source(string fileName) : this(new FileStream(fileName, FileMode.Open), false)
{

}

public void Dispose()
{
if (!_leaveOpen)
{
_stream?.Dispose();
}
}
}

关于c# - 构造函数链中的 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642873/

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