2017-03-01 103 views
0

我有一个对象是在给出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" 
    }; 
} 

该警告是 - ')的新的OpenFileDialog(' 警告CA2000在方法 'SIMPathFinder.SIMPathFinder()',对象不被沿所有的异常路径设置。调用System.IDisposable.Dispose对象的新OpenFileDialog()'之前,所有对它的引用超出范围。

+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窗体。您从Window继承(我认为这是System.Windows.Window,因为您的问题标记为),但请尝试使用System.Windows.Forms.OpenFileDialog
混合这两个UI框架不是一个好主意。改为使用Microsoft.Win32.OpenFileDialog

+0

当你所做的只是处理子对象时,没有必要实现终结器(你忽略了,但我猜它仍然存在,因为GC.SuppressFinalize(this))。 – Evk