2013-11-25 32 views
0

這個警告是非常討厭的,我已經閱讀了許多帖子建議周圍的方式,但他們似乎並沒有工作。CA2000:Microsoft.Reliability調用System.IDisposable.Dispose對象之前,所有對它的引用超出範圍

據我所見,我已經在下面的代碼中滿足了所有場景,但我仍然得到了警告。我正在使用VS2010。我試圖壓制它,但我寧願修復它,如果它不太難看。有什麼建議麼?

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

回答

3

這裏:

    if (value != null) 
         result = (value as Configuration).Solutions.LicenseModules; 

您分配一個result沒有已經配置實例的創建在這裏:

  result = new LicenseModules(); 

您應該創建一個塊並且之前配置舊的結果值分配新的:

    if (value != null) { 
         result.Dipose(); 
         result = (value as Configuration).Solutions.LicenseModules; 
        } 
+0

另一種選擇是刪除第一個賦值,並在外部'if'塊之下執行空檢查:'返回結果??新的LicenseModules();' – Stijn

+0

謝謝,我應該學會閱讀:) –

相關問題