我有一个在类级别声明的对象,它提供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"
};
}警告是-在方法'SIMPathFinder.SIMPathFinder()‘中警告SIMPathFinder.SIMPathFinder,对象'new ()’不是沿所有异常路径释放的。在所有对对象的引用超出作用域之前,在对象'new ()‘上调用OpenFileDialog。
发布于 2017-03-01 18:14:53
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);
}
}阅读更多关于处置模式的信息
作为附带说明:您似乎混合了WPF和Windows窗体。您继承了Window (我认为它是System.Windows.Window,因为您的问题被标记为wpf),但是尝试使用System.Windows.Forms.OpenFileDialog。
将这两个UI框架混合在一起并不是一个好主意。使用Microsoft.Win32.OpenFileDialog代替。
https://stackoverflow.com/questions/42538875
复制相似问题