【问题标题】:How can I implement Dispose for IDisposable without the code being recursive? [closed]如何在代码不递归的情况下为 IDisposable 实现 Dispose? [关闭]
【发布时间】:2014-06-18 16:00:18
【问题描述】:

我正在重构一些代码,在上面使用 Resharper,然后遇到了这个问题:

public virtual void Dispose()
{
    this.Dispose();
}

...哪个 R# 标记为“函数在所有路径上都是递归的

这是有道理的;但是,“官方”(straight from the horse's mouth)代码有些相似(Dispose 调用 Dispose):

public void Dispose()
{
    Dispose(true);
    // This object will be cleaned up by the Dispose method. 
    // Therefore, you should call GC.SupressFinalize to 
    // take this object off the finalization queue 
    // and prevent finalization code for this object 
    // from executing a second time.
    GC.SuppressFinalize(this);
}

...不过,该代码甚至无法编译;我得到,“方法 'Dispose' 没有重载需要 '1' 个参数”

那么我怎样才能既实现 Dispose() 又不让它递归呢?

更新

如果我试试这个(来自here):

try
{
    Dispose(true); //true: safe to free managed resources
}
finally
{
    base.Dispose();
}

...我明白了,“'object' 不包含 'Dispose' 的定义”和“方法 'Dispose' 没有重载需要 '1' 个参数”

【问题讨论】:

  • 两者显然不一样。 MSDN 示例从外部Dispose 内部调用不同的Dispose 方法。
  • 如果我们一开始看不到您实际需要处理的内容,没有人可以明智地告诉您应该调用什么。模式比较清晰,所以我不确定你不确定的地方。
  • 那么你为什么要实现 IDisposable 呢?大概你有一些资源可以处置。所以把它们处理掉。
  • 如果你实现了接口,那一定是因为你有一些东西要在你的类中处理。如果没有,请不要执行它...

标签: c# garbage-collection resharper dispose idisposable


【解决方案1】:

看来您需要正确实现 Dispose 模式:

public class MyThingWithResources : IDisposable
{
    ~MyTHingWithResources()
    {
        // This is a finalizer and is an optional part.
        // Finalizers are not generally required, and are 
        // intended for clearing up unmanaged resources
        // that your class might hold

        // Finalizers are called by the garbage collector
        // So you can never be sure when they are going to
        // be called.

        this.Dispose(false);
    }

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

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // if disposing is true, then the method 
            // is being called as part of a managed disposal
            // this means it should be safe to dispose of managed 
            // resources (.Net classes such as System.IO.Stream )
        }

        // If disposing is false, the Dispose method was called 
        // from the finaliser, so you're in the last chance saloon 
        // as far as tidying stuff up is concerned.
        // Only unmanaged resources (and the objects that wrap them)
        // should be tidied up in this scenario
    }
}

【讨论】:

  • 鉴于我们不知道他们想要处理什么,您怎么知道需要 IDisposable?此外,通常仅在处理非托管资源时才需要终结器/析构器。
  • 我的问题中显示了 Dispose();它不会为我编译。
  • @B.ClayShannon,Dispose() not 在您的问题中显示。诚实的问题——您是否了解 (a) 您正在查看的代码或 (b) 您想要完成的内容(以及为什么)?你这样做并不明显,如果你对实际问题没有一点了解,我们也无法帮助你。
  • 我只是想重构代码;我不确定它是如何工作的。不是我写的,而且非常晦涩。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 2019-06-16
相关资源
最近更新 更多