gpt4 book ai didi

c#-4.0 - 与 IDisposable 混淆

转载 作者:行者123 更新时间:2023-12-02 00:15:11 25 4
gpt4 key购买 nike

我对实现 IDisposable 的正确方法有一些挥之不去的疑虑。考虑以下场景...

public class Foo : IDisposable {...}

public class Bar : IDisposable {

private bool disposed = false;
private readonly Foo MyFoo;

public Bar() {
this.MyFoo = new Foo();
}
public Bar(Foo foo) {
this.MyFoo = foo;
}
~Bar() {
Dispose(false);
}

protected virtual void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
if (MyFoo != null) {
this.MyFoo.Dispose();
this.MyFoo = null;
}
}
this.disposed = true;
}
}

public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}

我的问题是:

1) 如果一个类创建了一个一次性对象,它是否应该在它自己的 Dispose() 方法中调用该对象的 Dispose() 方法?

2) 如果将一次性对象作为引用传递给类,该类是否仍应对该引用对象调用 Dispose() 方法,还是应该将其留给最初创建该对象的类?

上面的模式似乎经常出现(尤其是 DI),但我似乎无法找到正确构造它的具体示例。

最佳答案

请参阅优秀的 MSDN 文章 Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework

1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?

是的,它应该。否则,也会调用 Dispose。但这将使对象的生命周期至少增加 1 代。这是由于类定义中的终结器。请参阅上面的文章链接。

2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?

调用 Dispose 方法是调用者(更具体地说是创建实例的类)的责任。

关于c#-4.0 - 与 IDisposable 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13564026/

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