首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CA2000 :在对对象的所有引用超出作用域之前,Microsoft.Reliability调用对象的System.IDisposable.Dispose

CA2000 :在对对象的所有引用超出作用域之前,Microsoft.Reliability调用对象的System.IDisposable.Dispose
EN

Stack Overflow用户
提问于 2013-11-25 07:45:45
回答 1查看 1.7K关注 0票数 0

这个警告是非常恼人的,我已经看过一些文章,建议如何绕过它,但它们似乎不起作用。

据我所见,我已经处理了下面代码中的所有场景,但我仍然收到了警告。我正在使用VS2010。我很想压制它,但如果它不变得太丑,我宁愿把它修好。有什么建议吗?

代码语言:javascript
复制
    private LicenseModules CreateDataSource
    {
        get
        {
            // set default result
            LicenseModules result = null;

            try
            {
                result = new LicenseModules();

                // lookup the "Tools" class in the current entry assembly
                var lookup = Assembly.GetEntryAssembly().GetTypes().FirstOrDefault(item => item.Name.Equals("Tools", StringComparison.Ordinal));

                // ensure the lookup result is valid
                if (lookup != null)
                {
                    // lookup the Configuration property
                    var prop = lookup.GetProperty("Configuration", BindingFlags.Static | BindingFlags.Public);
                    // validate the lookup result
                    if (prop != null)
                    {
                        // read the current Configuration value
                        object value = prop.GetValue(lookup, null);
                        // ensure the read value is valid
                        if (value != null)
                            result = (value as Configuration).Solutions.LicenseModules;
                    }
                }

                // return current result
                return result;
            }
            catch (Exception)
            {
                if (result != null)
                {
                    result.Dispose();
                }

                throw;
            }                
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-25 07:49:58

在此:

代码语言:javascript
复制
                  if (value != null)
                        result = (value as Configuration).Solutions.LicenseModules;

在没有处理在这里创建的实例的情况下,您为result分配了一个新值:

代码语言:javascript
复制
            result = new LicenseModules();

在分配新的结果之前,您应该创建一个块并释放旧的结果值:

代码语言:javascript
复制
                  if (value != null) {
                       result.Dipose();
                        result = (value as Configuration).Solutions.LicenseModules;
                  }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20187138

复制
相关文章

相似问题

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