【发布时间】: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