类级别对象上的CA2000警告

时间:2017-03-01 18:04:36

标签: c# .net wpf ca2000

我有一个在类级别声明的对象,它给出了CA2000警告。如何从下面的代码中删除CA2000警告?

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"
    };
}

警告是 - 警告CA2000在方法'SIMPathFinder.SIMPathFinder()'中,对象'new OpenFileDialog()'未沿所有异常路径放置。在对所有引用超出范围之前,调用System.IDisposable.Dispose对象'new OpenFileDialog()'。

1 个答案:

答案 0 :(得分:0)

CA2000表示你的类的实例拥有一个一次性对象,在你的类的实例超出范围之前,该对象应该被释放以释放使用过的(非托管的)资源。

执行此操作的常见模式是实现IDisposable接口和protected virtual Dispose方法:

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); 

    }
}

详细了解Dispose-Pattern

作为旁注:看来你的混合WPF和Windows Forms。您继承自Window(我认为System.Windows.Window,因为您的问题被标记为),但请尝试使用System.Windows.Forms.OpenFileDialog。 混合使用这两个UI框架并不是一个好主意。请改用Microsoft.Win32.OpenFileDialog

相关问题