本文介绍了如何正确实现idisposable(c#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行Analyze>在我的C#Winforms应用程序上运行代码分析解决方案。我得到了这个:



CA1001拥有一次性字段的类型应该是一次性的,可以在'ExceptionLoggingService'上实现IDisposable,因为它创建了以下IDisposable类型的成员:'StreamWriter 。如果先前已经发布了'ExceptionLoggingService',那么将实现IDisposable的新成员添加到此类型将被视为对现有消费者的重大改变。



什么我试过了:



所以我加了它:



I ran Analyze > Run Code Analysis on Solution on my C# Winforms app. I got this:

CA1001Types that own disposable fields should be disposableImplement IDisposable on 'ExceptionLoggingService' because it creates members of the following IDisposable types: 'StreamWriter'. If 'ExceptionLoggingService' has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers.

What I have tried:

So I added it:

public class ExceptionLoggingService : IDisposable
{
	. . .

	public void Dispose()
        {
            _streamWriter.Dispose();
        }
        . . .





...但是运行Analyze>在解决方案上运行代码分析再次给我以下指纹:



CA1063正确实现IDisposable在'ExceptionLoggingService'上提供Dispose(bool)的可覆盖实现或标记密封的类型。对Dispose(false)的调用应该只清理本机资源。调用Dispose(true)应该清理托管和本机资源。





那我该怎么做安抚野兽?



...but running Analyze > Run Code Analysis on Solution again gives me the following fingerwag:

CA1063Implement IDisposable correctlyProvide an overridable implementation of Dispose(bool) on 'ExceptionLoggingService' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources.


So what must I do to appease the beast?

推荐答案


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

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (_streamWriter != null) _streamWriter.Dispose();
    }
}


这篇关于如何正确实现idisposable(c#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:20