简体   繁体   中英

CA2000 warning on Class Level Object

I have an object that is declared at the class level which is giving CA2000 warning. How can I get rid of the CA2000 warning from the code below?

public partial class someclass : Window
{
    System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog()
    {
        AddExtension = true,
        CheckFileExists = true,
        CheckPathExists = true,
        DefaultExt = "xsd",
        FileName = lastFileName,
        Filter = "XML Schema Definitions (*.xsd)|*.xsd|All Files (*.*)|*.*",
        InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop),
        RestoreDirectory = true,
        Title = "Open an XML Schema Definition File"
    };
}

The warning is- Warning CA2000 In method 'SIMPathFinder.SIMPathFinder()', object 'new OpenFileDialog()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new OpenFileDialog()' before all references to it are out of scope.

CA2000 says that instances of your class own a disposable object that should be disposed to free used (unmanaged) resources before the instance of your class gets out of scope.

A common pattern to do this is to implement the IDisposable interface and an protected virtual Dispose method:

public partial class someclass : Window, IDisposable // implement IDisposable
{
    // shortened for brevity
    System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            dlg.Dispose(); // dispose the dialog
    }

    public void Dispose() // IDisposable implementation
    {
        Dispose(true);
        // tell the GC that there's no need for a finalizer call
        GC.SuppressFinalize(this); 

    }
}

Read more about the Dispose-Pattern


As a side note: It seems your mixing WPF and Windows Forms. You inherit from Window (which I presume is System.Windows.Window as your question is tagged ), but try to use a System.Windows.Forms.OpenFileDialog .
To mix these two UI frameworks is not a good idea. Use Microsoft.Win32.OpenFileDialog instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM