gpt4 book ai didi

c# - 如何使用关闭方法正确实现处置模式 (CA1063)

转载 作者:可可西里 更新时间:2023-11-01 08:22:20 26 4
gpt4 key购买 nike

框架设计指南(第 2 版,第 327 页)说:

CONSIDER providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.

When doing so, it is important that you make the Close implementation identical to Dispose and consider implementing IDisposable.Dispose method explicitly.

所以,按照提供的示例,我得到了这个类:

public class SomeClass : IDisposable {
private SomeDisposable someInnerDisposable;

public void Open() {
this.someInnerDisposable = new SomeDisposable();
}

void IDisposable.Dispose() {
this.Close();
}

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

protected virtual void Dispose(bool disposing) {
if (disposing) {
this.someInnerDisposable.Dispose();
this.someInnerDisposable = null;
}
}
}

FxCop 似乎不喜欢这样:

CA1816 : Microsoft.Usage : 'SomeClass.Close()' calls 'GC.SuppressFinalize(object)', a method that is typically only called within an implementation of 'IDisposable.Dispose'. Refer to the IDisposable pattern for more information.

CA1816 : Microsoft.Usage : Change 'SomeClass.IDisposable.Dispose()' to call 'GC.SuppressFinalize(object)'. This will prevent unnecessary finalization of the object once it has been disposed and it has fallen out of scope.

CA1063 : Microsoft.Design : Modify 'SomeClass.IDisposable.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.

CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.

  • 如何使用关闭方法正确实现处置模式?

-或-

  • 如何抑制警告?

我试过了

[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly",
Justification = "Framework Design Guidelines say it's ok.")]
void IDisposable.Dispose()
{
this.Close();
}

但 FxCop 1.36 仍然会报告它们。

编辑:按照建议更改它会消除除此警告之外的所有内容:

CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.

编辑 2:确实缺少 CODE_ANALYSIS。谢谢。

最佳答案

改变它。

让 Close() 调用 this.Dispose() 并将逻辑放在 Dispose() 方法而不是 Close() 方法中。

----------------编辑后的更多信息----------------

此外,将声明更改为:

public void Dispose()

应该摆脱其他错误。由于您已将其声明为:

void IDisposable.Dispose()

它没有标记为公开和密封,FxCop 提示道。就个人而言,我更愿意避免错误而不是抑制错误。

关于c# - 如何使用关闭方法正确实现处置模式 (CA1063),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/630955/

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