首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类级对象上的CA2000警告

类级对象上的CA2000警告
EN

Stack Overflow用户
提问于 2017-03-01 18:04:35
回答 1查看 181关注 0票数 0

我有一个在类级别声明的对象,它提供CA2000警告。如何消除下面代码中的CA2000警告?

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-01 18:14:53

CA2000说,类的实例拥有一个一次性对象,在类的实例超出作用域之前,这些对象应该被处理为自由使用(非托管)资源。

这样做的一个常见模式是实现IDisposable接口和protected virtual Dispose方法:

代码语言:javascript
复制
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代替。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42538875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档