簡體   English   中英

從.Designer.cs文件禁用/修復代碼分析警告

[英]Disabling/Fixing Code Analysis warnings from .Designer.cs files

我正在廣泛使用DataVisualization.Charting.Chart ,並且在大多數情況下它正在工作。 但是,我經常運行代碼分析,並自己處理警告。 但是,使用圖表的* .Designer.cs文件中大約有30個CA2000(未沿所有異常路徑布置的對象)。 Designer文件幾乎生成了所有圖表代碼,幾乎所有圖表元素都實現了IDisposable 我在項目首選項中選中了“從生成的代碼中抑制結果”,但它仍然可以。

有沒有辦法解決這個問題,而不必手動創建圖表對象,並且不會禁用該類中其余代碼的代碼分析? 有沒有辦法為所有.Designer.cs文件禁用它? 或者,是否有解決方案通過使設計師代碼處理來正確刪除這些警告?

很少有開發人員似乎沒有運氣就遇到過這種情況,所以+1代表一個好問題!

一種可能的解決方案是編寫一個覆蓋CA2000的方法,並在設計器文件中檢測到警告時禁止該規則,這是一個好的開始:

在Visual Studio 2010中編寫自定義代碼分析規則

否則請參閱本主題末尾的評論,MSFT工程師提到記錄一個Connect調用: http//blogs.msdn.com/b/codeanalysis/archive/2010/03/22/what-s-new-in-代碼分析換視覺工作室2010.aspx

我知道我遲到了,但這里有。

我猜這些警告都是在InitializeComponent方法中為代碼發出的? 如果是,那么您是否考慮過修改位於Common7 \\ IDE \\ ItemTemplates文件夾中的模板文件? 您可以在方法中添加GeneratedCode屬性。 由於該屬性僅在其上設置,因此同一類中的所有其他代碼仍將通過代碼分析進行檢查。

以下是Form設計器文件的示例:

namespace $rootnamespace$
{
    partial class $safeitemrootname$
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        [System.CodeDom.Compiler.GeneratedCode("Windows Form Designer generated code", "1.0.0.0"), System.Diagnostics.DebuggerNonUserCode()]
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "$safeitemrootname$";
        }

        #endregion
    }
}

只需將[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "..."]到* .Designer.cs文件中的Dispose方法即可。

我剛剛做了,而且我發現VS 2012非常聰明,即使在設計師更改了某些內容時重寫文件也能保持它。

您是否嘗試在項目的“代碼分析”屬性頁中將“從生成的代碼中抑制結果”屬性值切換為true? 此選項是忽略生成代碼中的問題的標准機制。

也就是說,生成的代碼是將要執行的代碼,因此忽略其違規行為不一定是個好主意。 鑒於CA2000的“噪音”,您可能希望考慮禁用該規則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM