gpt4 book ai didi

c# - 在处置类实例时,我是否需要显式处置其所有 IDisposable 成员?

转载 作者:太空狗 更新时间:2023-10-29 18:24:41 24 4
gpt4 key购买 nike

我有一个类,它有一个 SqlConnection 类型的属性。 SqlConnection 实现了 IDisposable。我有以下问题:

  1. 我的类是否也应该实现 IDisposable 只是因为它具有 IDisposable 类型的属性?

  2. 如果是,我是否需要在处理我的类的实例时Dispose 显式 属性?例如

    public class Helper : IDisposable
    {
    // Assume that it's ANY OTHER IDisposable type. SqlConnection is just an example.
    public SqlConnection SqlConnection { get; set; }

    public void Dispose()
    {
    if (SqlConnection!= null)
    {
    SqlConnection.Dispose();
    }
    }
    }

注意:我知道在实现 IDisposable 时需要遵循一种模式,但我的问题是针对上述情况的。

最佳答案

甚至存在一个代码分析规则:CA1001: Types that own disposable fields should be disposable .

A class implements the IDisposable interface to dispose of unmanaged resources that it owns. An instance field that is an IDisposable type indicates that the field owns an unmanaged resource. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface.


编辑:以上答案始终对父类拥有IDisposable成员有效。

也就是说,成员的所有权对于像您这样的公共(public)属性来说有点模糊:如果 SqlConnection 实例是在您的类之外创建的,那么您的类很可能是 < em>不实际上拥有该实例,但除了您之外没有人知道。

关于 IDisposable 成员是否由其父类拥有有一个有趣的例子:StreamWriter。有很多关于它的问题,例如这个线程:Is there any way to close a StreamWriter without closing its BaseStream?

现在甚至有一个 leaveOpen 参数,因此 StreamWriter 不会释放其基本流。

关于c# - 在处置类实例时,我是否需要显式处置其所有 IDisposable 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31783402/

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