微軟編程規范(文檔)


項目編程規范

 

 

 

 

第一章 概述. 5

術語定義. 5

Pascal 大小寫. 5

Camel 大小寫. 5

文件命名組織. 5

1.3.1文件命名. 5

1.3.2文件注釋. 5

第二章   代碼外觀. 7

2.1  列寬. 7

2.2  換行. 7

2.3  縮進. 7

2.4  空行. 7

2.5  空格. 8

2.6  括號 - () 8

2.7  花括號 - {} 9

第三章 程序注釋. 10

3.1  注釋概述. 10

3.2  文檔型注釋. 10

3.3  單行注釋. 11

3.4  注釋標簽. 12

第四章 申明. 15

4.1  每行聲明數. 15

4.2  初始化. 15

4.3  位置. 15

4.4  類和接口的聲明. 16

4.5  字段的聲明. 16

第五章 命名規范. 17

5.1  命名概述. 17

5.2  大小寫規則. 18

5.3  縮寫. 19

5.4  命名空間. 19

5.5  類. 19

5.6  接口. 20

5.7  屬性 (Attribute) 21

5.8  枚舉 (Enum) 21

5.9  參數. 21

5.10   方法. 21

5.11   屬性 (property) 22

5.12   事件. 23

5.13   常量 (const) 24

5.14   字段. 25

5.15   靜態字段. 26

5.16   集合. 26

5.17   措詞. 26

第六章 語句. 28

6.1  每行一個語句. 28

6.2  復合語句. 28

6.3  return 語句. 28

6.4  if、 if-else、if else-if 語句. 28

6.4 for、foreach 語句. 29

6.5  while 語句. 30

6.7. do - while 語句. 30

6.8. switch - case 語句. 30

6.9. try - catch 語句. 31

6.10.  using 塊語句. 31

6.11.  goto 語句. 31

第七章   控件命名規則. 32

7.1  命名方法. 32

7.2  主要控件名簡寫對照表. 32

第八章 代碼格式檢查. 33

8.1 檢查分類. 33

8.2 安裝及使用. 33

8.3 文檔規則(Documentation Rules) 34

8.4 布局規則(LayoutRules) 42

8.5 可維護性規則(Maintanability Rules)”. 43

第九章 代碼分析. 45

9.1.安全性規則. 45

9.2.可靠性規則. 45

9.3.可維護性規則. 45

9.4.命名規則. 46

9.5.性能規則. 46

9.6.用法規則. 46

 

第一章 概述

1.1術語定義

1.1.1 Pascal 大小寫

將標識符的首字母和后面連接的每個單詞的首字母都大寫。可以對三字符或更多字符的標識符使用Pascal 大小寫。例如: BackColor

 

1.1.2 Camel 大小寫

標識符的首字母小寫,而每個后面連接的單詞的首字母都大寫。例如:backColor

 

第二章  代碼外觀

2.1  列寬

    代碼列寬控制在110字符左右。

2.2  換行

      當表達式超出或即將超出規定的列寬,遵循以下規則進行換行

          1、在逗號后換行;

          2、在操作符前換行;

          3、規則1優先於規則2。             

2.3  縮進

     縮進應該是每行一個Tab(4個空格),不要在代碼中使用Tab字符。

2.4  空行

空行是為了將邏輯上相關聯的代碼分塊,以便提高代碼的可閱讀性。

  在代碼中,不能包含多個空行。       

     

    在以下情況下使用一個空行

         1、方法與方法、屬性與屬性之間。

         2、方法中變量聲明與語句之間。

         3、方法與方法之間。

         4、方法中不同的邏輯塊之間。

        5、方法中的返回語句與其他的語句之間。

         6、屬性與方法、屬性與字段、方法與字段之間。

         7、注釋與它注釋的語句間不空行,但與其他的語句間空一行。

 

 

 

2.5  空格

在以下情況中要使用到空格

        1、 關鍵字和左括符 “(” 應該用空格隔開。如while (true)   

 

           注意:在方法名和左括符 “(” 之間不要使用空格,這樣有助於辨認代碼中的方法調用與關鍵字。

          

2、  多個參數用逗號隔開,每個逗號后都應加一個空格。

3、  除了 . 之外,所有的二元操作符都應用空格與它們的操作數隔開。一元操作符、++及--與操作數間不需要空格。如

 

                a  +=  c  +  d;

             a  =  (a  +  b)   /   (c  *  d);

                while  (d++  =  s++)

                {

                    n++;

                }

                PrintSize(“size is “  +  size  +  “\n”);

 

4、 語句中的表達式之間用空格隔開。如

 

       for  (expr1;  expr2;  expr3)

 

2.6  括號 - ()

      1、 左括號“(” 不要緊靠關鍵字,中間用一個空格隔開。

      2、 左括號“(”  與方法名之間不要添加任何空格。

      3、 沒有必要的話不要在返回語句中使用()。如

  

        if (condition)

 

            Array.Remove(1)

 

            return 1 

2.7  花括號 - {}

       1、 左花括號 “{” 放於關鍵字或方法名的下一行並與之對齊。如

 

             if (condition)

             {

             }

 

             public int Add(int x, int y)

             {

             }

 

                           2、 左花括號 “{” 要與相應的右花括號 “}”對齊。

       3、 通常情況下左花括號 “{”單獨成行,不與任何語句並列一行。

       4、 if、while、do語句后一定要使用{},即使{}號中為空或只有一條語句。如

 

             if (somevalue == 1)

             {

                 somevalue = 2;

             }

 

5、 右花括號 “}” 后建議加一個注釋以便於方便的找到與之相應的 {。如

 

               while  (1)

               {

                   if  (valid)

                   {

                   }

                   else

                   {

                   } // if

                } // while

第三章 程序注釋

3.1  注釋概述

1、修改代碼時,總是使代碼周圍的注釋保持最新。

2、在每個例程的開始,提供標准的注釋樣本以指示例程的用途、假設和限制很有幫助。注釋樣本應該是解釋它為什么存在和可以做什么的簡短介紹.

3、避免在代碼行的末尾添加注釋;行尾注釋使代碼更難閱讀。不過在批注變量聲明時,行尾注釋是合適的;在這種情況下,將所有行尾注釋在公共制表位處對齊。

4 、避免雜亂的注釋,如一整行星號。而是應該使用空白將注釋同代碼分開。

5 、避免在塊注釋的周圍加上印刷框。這樣看起來可能很漂亮,但是難於維護。

6 、在部署發布之前,移除所有臨時或無關的注釋,以避免在日后的維護工作中產生混亂。

7 、如果需要用注釋來解釋復雜的代碼節,請檢查此代碼以確定是否應該重寫它。盡一切可能不注釋難以理解的代碼,而應該重寫它。盡管一般不應該為了使代碼更簡單以便於人們使用而犧牲性能,但必須保持性能和可維護性之間的平衡。

8 、在編寫注釋時使用完整的句子。注釋應該闡明代碼,而不應該增加多義性。

9 、在編寫代碼時就注釋,因為以后很可能沒有時間這樣做。另外,如果有機會復查已編寫的代碼,在今天看來很明顯的東西六周以后或許就不明顯了。

10 、避免多余的或不適當的注釋,如幽默的不主要的備注。

11、 使用注釋來解釋代碼的意圖。它們不應作為代碼的聯機翻譯。

12、 注釋代碼中不十分明顯的任何內容。

13 、為了防止問題反復出現,對錯誤修復和解決方法代碼總是使用注釋,尤其是在團隊環境中。

14 、對由循環和邏輯分支組成的代碼使用注釋。這些是幫助源代碼讀者的主要方面。

15 、在整個應用程序中,使用具有一致的標點和結構的統一樣式來構造注釋。

16 、用空白將注釋同注釋分隔符分開。在沒有顏色提示的情況下查看注釋時,這樣做會使注釋很明顯且容易被找到。

17 、在所有的代碼修改處加上修改標識的注釋。

18 、為了是層次清晰,在閉合的右花括號后注釋該閉合所對應的起點。

    namespace Langchao.Procument.Web

{

} // namespace Langchao.Procument.Web

3.2    文件注釋

在每個文件頭必須包含以下注釋說明

// <copyright file="文件名.cs" company="HP">

//  Copyright (c) HP. All rights reserved.

// </copyright>

// <author>×××</author>

// <date> yyyy-mm-dd </date>

// <summary>文件功能描述</summary>

// <modify>

//      修改人:×××

//      修改時間:yyyy-mm-dd

//      修改描述:×××

//      版本:1.0

//</modify>

注意:文件功能描述只需簡述,具體詳情在類的注釋中描述。創建標識和修改標識由創建或修改人員的拼音或英文名。如:Zhangsan。一天內有多個修改的只需做一個在注釋說明中做一個修改標識就夠了。在所有的代碼修改處加上修改標識的注釋。

3.3    文檔型注釋

 該類注釋采用.Net已定義好的Xml標簽來標記,在聲明接口、類、方法、屬性、字段都應該使用該類注釋,以便代碼完成后直接生成代碼文檔,讓別人更好的了解代碼的實現和接口。如

1、  類、接口注釋

/// <summary>

    /// 類功能的說明

    /// </summary>

    /// <see cref=""></see>

    /// <remarks>

    /// 創建人:Zhangsan

    /// 創建日期:yyyy-mm-dd

    /// 修改人:Lisi

    /// 修改日期:yyyy-mm-dd

    /// 修改備注:無

    /// 版本:1.0

    /// </remarks>

    public class CountersModuleInitializer : ModuleInitializer

    {

}

注意:<see cref=""></see>標簽根據具體情況選擇有無

 

2、  方法、事件注釋

/// <summary>

        /// 根據員工編號獲得員工信息

        /// </summary>

        /// <param name="employeeId">員工編號</param>

        /// <exception cref="System.Exception">系統異常</exception>

        /// <returns>員工姓名</returns>

        /// <remarks>

        /// 創建人:Zhangsan

        /// 創建日期:yyyy-mm-dd

        /// 修改人:Lisi

        /// 修改日期:yyyy-mm-dd

        /// 修改備注:無

        /// 版本:1.1

        /// </remarks>

        public string GetEmployeeNameById(int employeeId)

        {

            try

            {

                return "ddd";

            }

            catch (System.Exception)

            {

                throw;

            }

}

注意:該方法注釋中的<param></param>、<exception cref=" "></exception>、<returns></returns>等標簽根據具體情況選擇有無,方法初始版本為1.0,每次改動增加0.1。

 

3、  屬性、常量注釋

/// <summary>

        /// session id

        /// </summary>

public const string SESSION_ID = "";

3.3  單行注釋

      該類注釋用於

1 方法內的代碼注釋。如變量的聲明、代碼或代碼段的解釋。注釋示例:

         // 注釋語句

         private int number;

    

          2 方法內變量的聲明或花括號后的注釋, 注釋示例:

if ( 1 == 1)    // always true

                {

                  statement;

                   }

                   else     // always false

                   {

}

3.4 JavaScript注釋

  a) 注釋符號

        ‘//’

        不允許使用‘/**/’作注釋符。

    b) 函數注釋

每個函數都應該描述該函數的名稱、功能、作用范圍、入口參數的類型和傳值方式及參數含義、返回值類型及返回值的含義。格式如下:

//

//Function:  函數名

//Purpose:   用途

//Scope:     作用范圍

//Args:      入口參數(列表)     類型傳值方式含義

//Returns:   返回值類型  (可確定值列表)  含義

//

c) 非函數注釋

   注明該模塊的作用

   格式如下:

//

//功能:

//

d) 程序行間注釋

   在程序行的每一個處理單元前作注釋

   格式如下:

   //注釋

e) 注釋舉例

     //

//Function:  F_FindObject

//Purpose:   按照空間名在可視化主對象中查找住對象內的可視化控件

//Scope:     Public

//Args:      is_name        String   value:要查找的空間名

//           ipbo_object    Object   value: 可視化主對象

//Returns:   Boolean        True     表示找到該控件

//                          False    表示沒有找到該控件

//

function F_FindObject(is_name, ipbo_object) {

 

    //獲得顯示學生信息的GreeView控件

    var gv_student = document.getElementById("GVStudent");

   

    ***********

   

    //返回true

    return true;

}

3.5  注釋標簽

    

標簽

用法

作用

<c>

c>text</c>

 

text 希望將其指示為代碼的文本。

為您提供了一種將說明中的文本標記為代碼的方法。使用 <code> 將多行指示為代碼

<para>

<para>content</para>

content段落文本。

用於諸如 <remarks><returns> 等標記內,使您得以將結構添加到文本中。

<param>

<param name='name'>description</param>

name 為方法參數名。將此名稱用單引號括起來 (' ')。

應當用於方法聲明的注釋中,以描述方法的一個參數。

<paramref>

 

<paramref name="name"/>

name

要引用的參數名。將此名稱用雙引號括起來 (" ")。

<paramref> 標記為您提供了一種指示詞為參數的方法。可以處理 XML 文件,從而用某種獨特的方法格式化該參數。

<see>

<see cref="member"/>

 

cref = "member" 對可以通過當前編譯環境進行調用的成員或字段的引用。編譯器檢查到給定代碼元素存在后,將 member 傳遞給輸出 XML 中的元素名。必須將 member 括在雙引號 (" ") 中。

使您得以從文本內指定鏈接。使用 <seealso> 指示希望在“請參閱”一節中出現的文本。

<seealso>

<seealso cref="member"/>

cref = "member" 對可以通過當前編譯環境進行調用的成員或字段的引用。編譯器檢查到給定代碼元素存在后,將 member 傳遞給輸出 XML 中的元素名。必須將 member 括在雙引號 (" ") 中

使您得以指定希望在“請參閱”一節中出現的文本。使用 <see> 從文本

<example>

<example>description</example>

description

代碼示例的說明。

使用 <example> 標記可以指定使用方法或其他庫成員的示例。一般情況下,這將涉及到 <code> 標記的使用。

<code>

<code>content</code>

content 為希望將其標記為代碼的文本。

 

記為您提供了一種將多行指示為代碼的方法。使用 <c> 指示應將說明中的文本標記為代碼

<summary>

<summary>description</summary>

此處description 為對象的摘要。

應當用於描述類型成員。使用 <remarks> 以提供有關類型本身的信息。

<exception>

<exception cref="member">description</exception>

cref = "member" 對可從當前編譯環境中獲取的異常的引用。編譯器檢查到給定異常存在后,將 member 轉換為輸出 XML 中的規范化元素名。必須將 member 括在雙引號 (" ") 中。

description 說明。

<exception> 標記使您可以指定類能夠引發的異常。

<include>

<include file='filename' path='tagpath[@name="id"]' />

filename 包含文檔的文件名。該文件名可用路徑加以限定。將 filename 括在單引號中 (' ')。

Tagpath:filename 中指向標記名的標記路徑。將此路徑括在單引號中 (' ')。

name 注釋前邊的標記中的名稱說明符;名稱具有一個 id

id

位於注釋之前的標記的 id。將此 id 括在雙引號中 (" ")。

<include> 標記使您得以引用描述源代碼中類型和成員的另一文件中的注釋。這是除了將文檔注釋直接置於源代碼文件中之外的另一種可選方法。

<include> 標記使用 XML XPath 語法。有關自定義 <include> 使用的方法,請參閱 XPath 文檔。

<list>

<list type="bullet" | "number" | "table">

   <listheader>

      <term>term</term>

      <description>description</description>

   </listheader>

   <item>

      <term>term</term>

      <description>description</description>

   </item>

</list>

 

term  定義的項,該項將在 text 中定義。

description  目符號列表或編號列表中的項或者 term 的定義。

<listheader> 塊用於定義表或定義列表中的標題行。定義表時,只需為標題中的項提供一個項。

列表中的每一項用 <item> 塊指定。創建定義列表時,既需要指定 term 也需要指定 text。但是,對於表、項目符號列表或編號列表,只需為 text 提供一個項。

列表或表所擁有的 <item> 塊數可以根據需要而定。

<permission>

<permission cref="member">description</permission>

 

cref = "member" 對可以通過當前編譯環境進行調用的成員或字段的引用。編譯器檢查到給定代碼元素存在后,將 member 轉換為輸出 XML 中的規范化元素名。必須將 member 括在雙引號 (" ") 中。

description  成員的訪問的說明。

<permission> 標記使您得以將成員的訪問記入文檔。System.Security.PermissionSet 使您得以指定對成員的訪問。

<remarks>

<remarks>description</remarks>

description 成員的說明。

<remarks> 標記是可以指定有關類或其他類型的概述信息的位置。<summary> 是可以描述該類型的成員的位置。

<returns>

<returns>description</returns>

description 返回值的說明。

<returns> 標記應當用於方法聲明的注釋,以描述返回值。

<value>

<value>property-description</value>

property-description 屬性的說明。

<value> 標記使您得以描述屬性。請注意,當在 Visual Studio .NET 開發環境中通過代碼向導添加屬性時,它將會為新屬性添加 <summary> 標記。然后,應該手動添加 <value> 標記以描述該屬性所表示的值。

 

第四章 申明

4.1 每行聲明數

一行只作一個聲明,如

 

          int level;   //推薦

          int size;    //推薦

          int x, y;    //不推薦

 

4.2 初始化

      建議在變量聲明時就對其做初始化。       

 

4.3 位置

      變量建議置於塊的開始處,不要總是在第一次使用它們的地方做聲明。如

 

         void MyMethod()

          {

              int int1 = 0;         // beginning of method block

 

if (condition)

{

                  int int2 = 0;     // beginning of "if" block

                  ...

              }

          }

 

        不過也有一個例外

       

                for (int i = 0; i < maxLoops; i++)

                {

                    ...

                }

 

        應避免不同層次間的變量重名,如

 

            int count;

            ...

void MyMethod()

{

                if (condition)

                {

                    int count = 0;     // 避免

                     ...

                 }

                 ...

}

 

4.4 類和接口的聲明

      1 在方法名與其后的左括號間沒有任何空格。

      2 左花括號 “{” 出現在聲明的下行並與之對齊,單獨成行。

      3 方法間用一個空行隔開。

    

4.5 字段的聲明

不要使用是 public 或 protected 的實例字段。如果避免將字段直接公開給開發人員,可以更輕松地對類進行版本控制,原因是在維護二進制兼容性時字段不能被更改為屬性。考慮為字段提供 get 和set 屬性訪問器,而不是使它們成為公共的。 get 和 set 屬性訪問器中可執行代碼的存在使得可以進行后續改進,如在使用屬性或者得到屬性更改通知時根據需要創建對象。下面的代碼示例闡釋帶有get 和 set 屬性訪問器的私有實例字段的正確使用。 示例:

            public class Control: Component

            {

               private int handle;

               public  int Handle

               {

                  get

                  {

                     return handle;

                  }

               }

}

第五章 命名規范

 

5.1 命名概述

名稱應該說明“什么”而不是“如何”。通過避免使用公開基礎實現(它們會發生改變)的名稱,可以保留簡化復雜性的抽象層。例如,可以使用 GetNextStudent(),而不是 GetNextArrayElement()。

命名原則是:

選擇正確名稱時的困難可能表明需要進一步分析或定義項的目的。使名稱足夠長以便有一定的意義,並且足夠短以避免冗長。唯一名稱在編程上僅用於將各項區分開。表現力強的名稱是為了幫助人們閱讀;因此,提供人們可以理解的名稱是有意義的。不過,請確保選擇的名稱符合適用語言的規則和標准。

以下幾點是推薦的命名方法。

1、避免容易被主觀解釋的難懂的名稱,如方面名 AnalyzeThis(),或者屬性名 xxK8。這樣的名稱會導致多義性。

2、在類屬性的名稱中包含類名是多余的,如 Book.BookTitle。而是應該使用 Book.Title。

3、只要合適,在變量名的末尾或開頭加計算限定符(Avg、Sum、Min、Max、Index)。

4、在變量名中使用互補對,如 min/max、begin/end 和 open/close。

5、布爾變量名應該包含 Is,這意味着 Yes/No 或 True/False 值,如 fileIsFound。

6、在命名狀態變量時,避免使用諸如 Flag 的術語。狀態變量不同於布爾變量的地方是它可以具有兩個以上的可能值。不是使用 documentFlag,而是使用更具描述性的名稱,如 documentFormatType。 (此項只供參考)

7、即使對於可能僅出現在幾個代碼行中的生存期很短的變量,仍然使用有意義的名稱。僅對於短循環索引使用單字母變量名,如 i 或 j。 可能的情況下,盡量不要使用原義數字或原義字符串,如

For i = 1 To 7。而是使用命名常數,如 For i = 1 To NUM_DAYS_IN_WEEK 以便於維護和理解。

8、用於事件處理的委托添加“EventHandler”后綴
9、用於事件處理之外的那些委托添加“Callback”后綴
10、不要給委托添加“Delegate”后綴

11、用名詞或名詞詞組來給類型命名,在少數情況下也可以用形容詞詞組來給類型命名

12、用動詞或動詞詞組來命名方法

13、用名詞、名詞詞組或形容詞來命名屬性

14、要用動詞或動詞短語來命名事件

15、要用名詞或名詞短語來命名字段

 

5.2 大小寫規則

大寫

標識符中的所有字母都大寫。僅對於由兩個或者更少字母組成的標識符使用該約定。例如:

 

System.IO

System.Web.UI

 

下表匯總了大寫規則,並提供了不同類型的標識符的示例。

 

標識符

大小寫

樣例

名字空間

Pascal

namespace System.Security{ … }

類型

Pascal

public class StreamReader{ … }

接口

Pascal

public interface IEnumerable{ … }

方法

Pascal

public class Object {

public virtual string ToString();

}

屬性

Pascal

public class String {

public int Length{ get; }

}

事件

Pascal

public class Process{

public event EventHandler Exited;

}

字段(私有實例)

Camel

private string userName

字段(公共靜態)

Pascal

public static readonly string UserId;

枚舉

Pascal

enum FileMode { Append, … }

參數

Camel

public class Convert {

public static int ToInt32(string userId);

}

 

 

5.3 縮寫

      為了避免混淆和保證跨語言交互操作,請遵循有關區縮寫的使用的下列規則:

      1 不要將縮寫或縮略形式用作標識符名稱的組成部分。例如,使用 GetWindow,而不要使用 GetWin。

      2 不要使用計算機領域中未被普遍接受的縮寫。

3 在適當的時候,使用眾所周知的縮寫替換冗長的詞組名稱。例如,用 UI 作為 User Interface 縮

寫,用 OLAP 作為 On-line Analytical Processing 的縮寫。

4在使用縮寫時,對於超過兩個字符長度的縮寫請使用 Pascal 大小寫或 Camel 大小寫。例如,使用 HtmlButton 或 HTMLButton。但是,應當大寫僅有兩個字符的縮寫,如,System.IO,而不是 System.Io。

5 不要在標識符或參數名稱中使用縮寫。如果必須使用縮寫,對於由多於兩個字符所組成的縮寫請

使用Camel 大小寫,雖然這和單詞的標准縮寫相沖突。

 

5.4 命名空間

      1、給命名空間命名時的一般性規則是使用公司名稱,后跟技術名稱和可選的功能與設計,如下所示。

            CompanyName.TechnologyName[.Feature][.Design]

        例如:

         namespace JadeBird.StudentManager             //學員系統

         namespace JadeBird.StudentManager.Register       //北學員注冊模塊

 

      2、命名空間使用Pascal大小寫,用點號分隔。

3、TechnologyName 指的是該項目的英文縮寫,或軟件名。
4、命名空間和類不能使用同樣的名字。例如,有一個類被命名為Debug后,就不要再使用Debug作為一個名稱空間名。

5.5 文件命名

1 文件名遵從Pascal命名法,無特殊情況,擴展名小寫。

2 使用統一而又通用的文件擴展名:

文件類型

擴展名

C#類

.cs

Asp.net頁面

.aspx

使用默認擴展名

 

5.6 類

1、使用 Pascal 大小寫。

2、用名詞或名詞短語命名類。

3、使用全稱避免縮寫,除非縮寫已是一種公認的約定,如URL、HTML   

4 、不要使用類型前綴,如在類名稱上對類使用 C 前綴。例如,使用類名稱 FileStream,而不是

CFileStream。

5 、不要使用下划線字符 (_)。

6 、有時候需要提供以字母 I 開始的類名稱,雖然該類不是接口。只要 I 是作為類名稱組成部分的整個單詞的第一個字母,這便是適當的。例如,類名稱 IdentityStore 是適當的。在適當的地方,使用復合單詞命名派生的類。派生類名稱的第二個部分應當是基類的名稱。例如,ApplicationException 對於從名為 Exception 的類派生的類是適當的名稱,原因ApplicationException 是一種Exception。請在應用該規則時進行合理的判斷。例如,Button 對於從 Control 派生的類是適當的名稱。盡管按鈕是一種控件,但是將 Control 作為類名稱的一部分將使名稱不必要地加長。

 

            public class FileStream

            public class Button

public class String

 

   

5.7 接口

      以下規則概述接口的命名指南:

      1、用名詞或名詞短語,或者描述行為的形容詞命名接口。例如,接口名稱 IComponent 使用描述性

名詞。接口名稱 ICustomAttributeProvider 使用名詞短語。名稱 IPersistable 使用形容詞。

2、使用 Pascal 大小寫。

      3、少用縮寫。

4、給接口名稱加上字母 I 前綴,以指示該類型為接口。在定義類/接口對(其中類是接口的標准

實現)時使用相似的名稱。兩個名稱的區別應該只是接口名稱上有字母 I 前綴。

 

5、不要使用下划線字符 (_)。

6、當類是接口的標准執行時,定義這一對類/接口組合就要使用相似的名稱。兩個名稱的不同之處

只是接口名前有一個I前綴。

 

          以下是正確命名的接口的示例。

 

                public interface IServiceProvider

                public interface IFormatable

 

          以下代碼示例闡釋如何定義 IComponent 接口及其標准實現 Component 類。

 

               public interface IComponent

               {

                   // Implementation code goes here.

               }

              

               public class Component: IComponent

               {

                   // Implementation code goes here.

}

 

5.8 枚舉 (Enum)

       枚舉 (Enum) 值類型從 Enum 類繼承。以下規則概述枚舉的命名指南:

           1 對於 Enum 類型和值名稱使用 Pascal 大小寫。

           2 少用縮寫。

           3 不要在 Enum 類型名稱上使用 Enum 后綴。

           4 對大多數 Enum 類型使用單數名稱,但是對作為位域的 Enum 類型使用復數名稱。

           5 總是將 FlagsAttribute 添加到位域 Enum 類型。

           6不要命名“Reserved”枚舉值。

 

5.9 參數

       以下規則概述參數的命名指南:

           1、使用描述性參數名稱。參數名稱應當具有足夠的描述性,以便參數的名稱及其類型可用於在大多數情況下確定它的含義。

       2、對參數名稱使用 Camel 大小寫。

           3、 使用描述參數的含義的名稱,而不要使用描述參數的類型的名稱。開發工具將提供有關參數的類型的有意義的信息。因此, 通過描述意義,可以更好地使用參數的名稱。少用基於類型的參數名稱,僅在適合使用它們的地方使用它們。

           4、不要使用保留的參數。保留的參數是專用參數,如果需要,可以在未來的版本中公開它們。相反,如果在類庫的未來版本中需要更多的數據,請為方法添加新的重載。

           5、不要給參數名稱加匈牙利語類型表示法的前綴。

       以下是正確命名的參數的示例。

 

               Type GetType(string typeName)

string Format(string format, args() As object)

5.10  方法

       以下規則概述方法的命名指南:

           1 使用動詞或動詞短語命名方法。

           2 使用 Pascal 大小寫。

           3 以下是正確命名的方法的實例。

 

              RemoveAll()

              GetCharArray()

Invoke()

 

 

5.11  屬性 (property)

        以下規則概述屬性的命名指南:

            1 使用名詞或名詞短語命名屬性。

            2 使用 Pascal 大小寫。

            3 不要使用匈牙利語表示法。

4 考慮用與屬性的基礎類型相同的名稱創建屬性。例如,如果聲明名為 Color 的屬性,則屬

性的類型同樣應該是 Color。請參閱本主題中后面的示例。

 

          以下代碼示例闡釋正確的屬性命名。

 

                 public class SampleClass

                 {

                      public Color BackColor

                      {

                           // Code for Get and Set accessors goes here.

                       }

                  }

 

            以下代碼示例闡釋提供其名稱與類型相同的屬性。

 

                 public enum Color

                 {

                     // Insert code for Enum here.

                  }

 

 

                  public class Control

{

                       public Color Color

                       {

get

{

// Insert code here.

}

set

{

// Insert code here.

}

                        }

                   }

 

           以下代碼示例不正確,原因是 Color 屬性是 Int 類型的。

 

                public enum Color

{

// Insert code for Enum here.

}

 

 

                public class Control

                {

                    public int Color

                    {

                        // Insert code here

                     }

                }

 

           在不正確的示例中,不可能引用 Color 枚舉的成員。Color.Xxx 將被解釋為訪問一個成員,

該成員首先獲取 Color 屬性( C# 中為 int 類型)的值,然后再訪問該值的某個成員(該成

員必須是 System.Int32 的實例成員)。

 

 

5.12  事件

        以下規則概述事件的命名指南:

            1、對事件處理程序名稱使用 EventHandler 后綴。

2、指定兩個名為 sender 和 e 的參數。sender 參數表示引發事件的對象。sender 參始

終是object 類型的,即使在可以使用更為特定的類型時也如此。與事件相關聯的狀態封裝

在名為 e 的事件類的實例中。對 e 參數類型使用適當而特定的事件類。

3、用 EventArgs 后綴命名事件參數類。

    4、考慮用動詞命名事件。

5、使用動名詞(動詞的“ing”形式)創建表示事件前的概念的事件名稱,用過去式表示事

件后。例如,可以取消的 Close 事件應當具有 Closing 事件和 Closed 事件。不要使用

BeforeXxx/AfterXxx 命名模式。

            6、不要在類型的事件聲明上使用前綴或者后綴。例如,使用 Close,而不要使用 OnClose。

7、通常情況下,對於可以在派生類中重寫的事件,應在類型上提供一個受保護的方法(稱為

OnXxx)。此方法只應具有事件參數 e,因為發送方總是類型的實例。

 

    以下示例闡釋具有適當名稱和參數的事件處理程序。

 

            public delegate void MouseEventHandler(object sender, MouseEventArgs e);

 

      以下示例闡釋正確命名的事件參數類。

 

                public class MouseEventArgs : EventArgs

                {

                   int x;

               int y;

 

                  public MouseEventArgs(int x, int y)

                  {

this.x = x;

this.y = y;

}

 

                  public int X

                  {

                      get

                      {

                          return x;

                      }

                  }

 

                  public int Y

                  {

                 get

                       {

                           return y;

                       }

                  }

                }

 

5.13  常量 (const)

        以下規則概述常量的命名指南:

        所有單詞大寫,多個單詞之間用 "_" 隔開。 如

 

                 public const string PAGE_TITLE = "Welcome";

          

 

5.14  字段

        以下規則概述字段的命名指南:

            1、private、protected 使用 Camel 大小寫。

            2、public 使用 Pascal 大小寫。

3、拼寫出字段名稱中使用的所有單詞。僅在開發人員一般都能理解時使用縮寫。字段名稱不

要使用大寫字母。下面是正確命名的字段的示例。

 

                class SampleClass

                {

                    string url;

            string destinationUrl;

}

 

            4、不要對字段名使用匈牙利語表示法。好的名稱描述語義,而非類型。

5、不要對字段名或靜態字段名應用前綴。具體說來,不要對字段名稱應用前綴來區分靜態和非靜態字段。例如,應用 g_ 或 s_ 前綴是不正確的。

6、對預定義對象實例使用公共靜態只讀字段。如果存在對象的預定義實例,則將它們聲明為

對象本身的公共靜態只讀字段。使用 Pascal 大小寫,原因是字段是公共的。下面的代碼

示例闡釋公共靜態只讀字段的正確使用。

 

                  public struct Color

                  {

                      public static readonly Color Red = new Color(0x0000FF);

 

                      public Color(int rgb)

{

 // Insert code here.}

                          public Color(byte r, byte g, byte b)

                          {

// Insert code here.

                           }

 

                      public byte RedValue

                      {

                           get

                           {

                                return Color;

                           }

                       }

                   }

5.15  靜態字段

       以下規則概述靜態字段的命名指南:

           1、使用名詞、名詞短語或者名詞的縮寫命名靜態字段。

           2、使用 Pascal 大小寫。

           3、對靜態字段名稱使用匈牙利語表示法前綴。

           4、建議盡可能使用靜態屬性而不是公共靜態字段。

 

5.16  集合

     集合是一組組合在一起的類似的類型化對象,如哈希表、查詢、堆棧、字典和列表,集合的命名

建議用復數。

 

5.17  措詞

避免使用與常用的 .NET 框架命名空間重復的類名稱。例如,不要將以下任何名稱用作類名稱:

System、Collections、Forms 或 UI。有關 .NET 框架命名空間的列表,請參閱類庫。

另外,避免使用和以下關鍵字沖突的標識符。

AddHandler

AddressOf

Alias

And

Ansi

As

Assembly

Auto

Base

Boolean

ByRef

Byte

ByVal

Call

Case

Catch

CBool

CByte

Cchar

CDate

CDec

CDbl

Char

Cint

Class

CLng

CObj

Const

Cshort

CSng

CStr

CType

Date

Decimal

Declare

Default

Delegate

Dim

Do

Double

Each

Else

ElseIf

End

Enum

Erase

Error

Event

Exit

ExternalSource

False

Finalize

Finally

Float

For

Friend

Function

Get

GetType

Goto

Handles

If

Implements

Imports

In

Inherits

Integer

Interface

Is

Let

Lib

Like

Long

Loop

Me

Mod

Module

MustInherit

MustOverride

MyBase

MyClass

Namespace

New

Next

Not

Nothing

NotInheritable

NotOverridable

Object

On

Option

Optional

Or

Overloads

Overridable

Overrides

ParamArray

Preserve

Private

Property

Protected

Public

RaiseEvent

ReadOnly

ReDim

Region

REM

RemoveHandler

Resume

Return

Select

Set

Shadows

Shared

Short

Single

Static

Step

Stop

String

Structure

Sub

SyncLock

Then

Throw

To

True

Try

TypeOf

Unicode

Until

volatile

When

While

With

WithEvents

WriteOnly

Xor

Eval

extends

instanceof

package

var

   

   

 

第六章 語句

6.1 每行一個語句

         每行最多包含一個語句。如

             a++;       //推薦

             b--;       //推薦

a++; b--;  //不推薦

 

6.2  復合語句

復合語句是指包含"父語句{子語句;子語句;}"的語句,使用復合語句應遵循以下幾點

            1 子語句要縮進。

2 左花括號“{” 在復合語句父語句的下一行並與之對齊,單獨成行。

3 即使只有一條子語句要不要省略花括號“ {}”。 如

                  while  (d + =  s++)

                  {

                      n++;

                    }

     

6.3  return 語句

        return語句中不使用括號,除非它能使返回值更加清晰。如

 

              return;

              return myDisk.size();

              return (size ? size : defaultSize);

6.4  if、 if-else、if else-if 語句

        if、 if-else、if else-if 語句使用格式

 

            if (condition)

            {

                statements;

            }

            if (condition)

            {

                statements;

            }

            else

            {

                statements;

            }

 

            if (condition)

            {

                statements;

            }

            else if (condition)

            {

                statements;

            }

            else

            {

                statements;

            }

        

 

6.4 for、foreach 語句

        for 語句使用格式

 

            for (initialization; condition; update)

            {

                statements;

            }

 

       空的 for 語句(所有的操作都在initialization、condition 或 update中實現)使用格式

 

              for (initialization; condition; update);    // update user id

       

       foreach 語句使用格式

 

              foreach (object obj in array)

              {

                  statements;

}

 

        注意1在循環過程中不要修改循環計數器。

           2對每個空循環體給出確認性注釋。

     

6.5  while 語句

        while 語句使用格式

 

            while (condition)

            {

                statements;

            }

 

         空的 while 語句使用格式

   

              while (condition);

 

 

6.7.  do - while 語句

         do - while 語句使用格式

              do

              {

                  statements;

              } while (condition);       

       

6.8.  switch - case 語句

         switch - case  語句使用格式

              switch (condition)

              {

                     case 1:

                         statements;

                         break;

 

                     case 2:

                         statements;

                         break;

 

                     default:

                         statements;

                         break;

                 }

 

           注意:

               1、語句switch中的每個case各占一行。

               2、語句switch中的case按字母順序排列。

               3、為所有switch語句提供default分支。

               4、所有的非空 case 語句必須用 break; 語句結束。

 

 

6.9.  try - catch 語句      

          try - catch  語句使用格式

              try

              {

                  statements;

              }

              catch (ExceptionClass e)

              {

                  statements;

              }

              finally

              {

                statements;

              }

   

6.10.    using 塊語句      

         using 塊語句使用格式

             using (object)

             {

                 statements;

             }

 

6.11.    goto 語句      

  goto 語句使用格式

             goto Label1:

                 statements;

              Lable1:

                  statements;

 

第七章 控件命名規則

7.1  命名方法

控件名簡寫+英文描述,英文描述首字母大寫

7.2  主要控件名簡寫對照表

控件名

簡寫

控件名

簡寫

Label

lbl

TextBox

txt

Button

btn

LinkButton

lnkbtn

ImageButton

imgbtn

DropDownList

ddl

ListBox

lst

DataGrid

dg

DataList

dl

CheckBox

chk

CheckBoxList

chkls

RadioButton

rdo

RadioButtonList

rdolt

Image

img

Panel

pnl

Calender

cld

AdRotator

ar

Table

tbl

RequiredFieldValidator

rfv

CompareValidator

cv

RangeValidator

rv

RegularExpressionValidator

rev

ValidatorSummary

vs

CrystalReportViewer

rptvew

 

 

第八章 代碼格式檢查

代碼格式檢查使用微軟內部代碼檢查工具 StyleCop 版本4.3.2.1,它會根據預定義的C#代碼格式的最佳實踐,對源代碼進行檢查,並給出不符合編碼風格的錯誤提示(版本語言英文)。

 

8.1 檢查分類

檢查規則分為7個部分,分別是

“文檔規則(Documentation Rules)”

“布局規則(LayoutRules)”

“可維護性規則(Maintanability Rules)”

“命名規則(Naming Rules)”

“代碼順序規則(Ordering Rules)”

“可讀性規則(Readability Rules)”

“間距規則(Spacing Rules)”

 

8.2 安裝及使用

安裝:安裝程序位於附件,Install文件夾中。該軟件屬於Visual Studio插件,安裝后在工具菜單欄中。

 

使用:運行該功能后,可以根據“錯誤列表”中的警告信息的信息Id,從幫助文件(位於附件,Document文件夾中,文件名StyleCop.chm)找到相應編碼格式,進行修復。

 

 



開發文檔:位於附件,Document文件夾中,文件名StyleCopSDK.chm)

 

對於以下情況 “是否檢查”一項中為“√”的內容不能違反。

8.3 文檔規則(Documentation Rules)

標識及提示

中文及示例

是否檢查

SA1600: ElementsMustBeDocumented

元素必須被注釋

/// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

}

SA1601: PartialElementsMustBeDocumented

部分元素必須被注釋

/// <summary>

    /// Documentation for the first part of Class1.

    /// </summary>

    public partial class Class1

    {

    }

 

    /// <summary>

    /// Documentation for the second part of Class1.

    /// </summary>

    public partial class Class1

    {

}

SA1602: EnumerationItemsMustBeDocumented

枚舉項必須被注釋

/// <summary>

    /// Types of animals.

    /// </summary>

    public enum Animals

    {

        /// <summary>

        /// Represents a dog.

        /// </summary>

        Dog,

 

        /// <summary>

        /// Represents a cat.

        /// </summary>

        Cat,

 

        /// <summary>

        /// Represents a horse.

        /// </summary>

        Horse

    }

SA1603: DocumentationMustContainValidXml

文檔必須包含有效的XML注釋

    /// <summary>

    /// An example of badly formed Xml.

    /// </summa3ry>

    public class Example

    {

    }

SA1604: ElementDocumentationMustHaveSummary

文檔注釋必須包含Summary

    /// <summary>

    /// Represents a customer in the database.

    /// </summary>

    public class Customer

    {

    }

SA1605: PartialElementDocumentationMustHaveSummary

部分文檔注釋必須包含Summary

/// <summary>

    /// Documentation for the first part of Class1.

    /// </summary>

    public partial class Class1

    {

    }

 

    /// <summary>

    /// Documentation for the second part of Class1.

    /// </summary>

    public partial class Class1

    {

    }

SA1606: ElementDocumentationMustHaveSummaryText

文檔注釋Summary必須有內容

/// <summary>  </summary>

/// <param name="customerId">The ID of the customer to find.</param>

/// <returns>The customer, or null if the customer could not be

/// found.</returns>

public Customer FindCustomer(int customerId)

{

    // ... finds the customer ...

}

SA1607: PartialElementDocumentationMustHaveSummaryText

部分文檔注釋Summary必須有內容

/// <summary>  </summary>

/// <param name="customerId">The ID of the customer to find.</param>

/// <returns>The customer, or null if the customer could not be found.</returns>

public Customer FindCustomer(int customerId)

{

    // ... finds the customer ...

}

 

修復代碼

/// <summary>Attempts to locate a record for the customer with the given ID.</summary>

/// <param name="customerId">The ID of the customer to find.</param>

/// <returns>The customer, or null if the customer could not be found.</returns>

public Customer FindCustomer(int customerId)

{

    // ... finds the customer ...

}

SA1608: ElementDocumentationMustNotHaveDefaultSummary

文檔注釋不能有默認的Summary

    /// <summary>

    /// Summary description for the Example class.

    /// </summary>

    public class Example

    {

    }

SA1609: PropertyDocumentationMustHaveValue

屬性注釋必須有值

  /// <summary>

    /// Gets the name of the customer.

    /// </summary>

    /// <value>The name of the customer.</value>

    public bool Name

    {

        get { return this.name; }

    }

SA1610: PropertyDocumentationMustHaveValueText

屬性注釋必須有值內容

  /// <summary>

    /// Gets the name of the customer.

    /// </summary>

    /// <value>The name of the customer.</value>

    public bool Name

    {

        get { return this.name; }

    }

SA1611: ElementParametersMustBeDocumented

元素的參數必須注釋

/// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1612: ElementParameterDocumentationMustMatchElementParameters

元素的參數注釋必須與元素參數成對

   /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1613: ElementParameterDocumentationMustDeclareParameterName

元素的參數注釋必須定義參數名

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1614: ElementParameterDocumentationMustHaveText

元素的參數注釋必須有值

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1615: ElementReturnValueMustBeDocumented

元素的返回值必須被注釋

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1616: ElementReturnValueDocumentationMustHaveValue

元素的返回值注釋必須有值

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1617: VoidReturnValueMustNotBeDocumented

元素空返回值不能注釋

   /// <summary>

    /// Prints the given name.

    /// </summary>

    /// <param name="firstName">The first name.</param>

    /// <param name="lastName">The last name.</param>

    public void PrintNames(string firstName, string lastName)

    {

        Console.WriteLine(firstName + " " + lastName);

    }

SA1618: GenericTypeParametersMustBeDocumented

泛型參數必須被注釋

   /// <summary>

    /// A sample generic class.

    /// </summary>

    /// <typeparam name="S">The first generic type parameter.</typeparam>

    /// <typeparam name="T">The second generic type parameter.</typeparam>

    public class Class1<S, T>

    {

    }

SA1619: GenericTypeParametersMustBeDocumentedPartialClass

泛型參數在部分類中必須被注釋

   /// <summary>

    /// A sample generic class.

    /// </summary>

    /// <typeparam name="S">The first generic type parameter.</typeparam>

    /// <typeparam name="T">The second generic type parameter.</typeparam>

    public class Class1<S, T>

    {

    }

SA1620: GenericTypeParameterDocumentationMustMatchTypeParameters

泛型參數注釋必須與參數類型對應

    /// <summary>

    /// A sample generic class.

    /// </summary>

    /// <typeparam name="S">The first generic type parameter.</typeparam>

    /// <typeparam name="T">The second generic type parameter.</typeparam>

    public class Class1<S, T>

    {

    }

SA1621: GenericTypeParameterDocumentationMustDeclareParameterName

泛型參數注釋必須定義參數名

    /// <summary>

    /// A sample generic class.

    /// </summary>

    /// <typeparam name="S">The first generic type parameter.</typeparam>

    /// <typeparam name="T">The second generic type parameter.</typeparam>

    public class Class1<S, T>

    {

    }

SA1622: GenericTypeParameterDocumentationMustHaveText

泛型參數注釋必須有內容

    /// <summary>

    /// A sample generic class.

    /// </summary>

    /// <typeparam name="S">The first generic type parameter.</typeparam>

    /// <typeparam name="T">The second generic type parameter.</typeparam>

    public class Class1<S, T>

    {

    }

SA1623: PropertySummaryDocumentationMustMatchAccessors

屬性摘要文檔必須和訪問者對應

(參考幫助文檔)

SA1624: PropertySummaryDocumentationMustOmitSetAccessorWithRestricedAccess

屬性摘要文檔必須必須省略設置訪問器約束訪問

(參考幫助文檔)

SA1625: ElementDocumentationMustNotBeCopiedAndPasted

元素注釋不能被拷貝和粘貼

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1626: SingleLineCommentsMustNotUseDocumentationStyleSlashes

單行注釋不能使用斜線樣式

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">Part of the name.</param>

    /// <param name="lastName">Part of the name.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

A legal comment beginning with two slashes:

        // Join the names together.

        string fullName = firstName + " " + lastName;

 

An illegal comment beginning with three slashes:

        /// Trim the name.

        fullName = fullName.Trim();

 

A line of commented-out code beginning with four slashes:

        ////fullName = asfd;

 

        return fullName;

    }

SA1627: DocumentationTextMustNotBeEmpty

注釋內容不能為空

    /// <summary>

    /// Joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName"> </param>

    /// <param name="lastName">Part of the name.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        ...

    }

SA1628: DocumentationTextMustBeginWithACapitalLetter

注釋內容首字母必須大寫

    /// <summary>

    /// joins a first name and a last name together into a single string.

    /// </summary>

    /// <param name="firstName">The first name.</param>

    /// <param name="lastName">The last name.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        ...

    }

SA1629: DocumentationTextMustEndWithAPeriod

注釋內容必須用句號結尾

    /// <summary>

    /// Joins a first name and a last name together into a single string

    /// </summary>

    /// <param name="firstName">The first name.</param>

    /// <param name="lastName">The last name.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        ...

    }

SA1630: DocumentationTextMustContainWhitespace

注釋內容單詞之間必須包含空白符

    /// <summary>

    /// Joinsnames

    /// </summary>

    /// <param name="firstName">First</param>

    /// <param name="lastName">Last</param>

    /// <returns>Name</returns>

    public string JoinNames(string firstName, string lastName)

    {

        ...

    }

 

SA1631: DocumentationTextMustMeetCharacterPercentage

注釋內容必須滿足字符比例特殊字符不能過多

    /// <summary>

    /// @)$(*A name--------

    /// </summary>

    public class Name   

    {

        ...

    }

 

SA1632: DocumentationTextMustMeetMinimumCharacterLength

注釋內容必須滿足小寫字符長度

    /// <summary>

    /// A name

    /// </summary>

    public class Name   

    {

        ...

    }

SA1633: FileMustHaveHeader

文件必須有文件頭部注釋

//-----------------------------------------------------------------------

// <copyright file="NameOfFile.cs" company="CompanyName">

//     Company copyright tag.

// </copyright>

//-----------------------------------------------------------------------

 

For example, a file called Widget.cs from a fictional company called Sprocket Enterprises should contain a file header similar to the following:

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

 

The dashed lines at the top and bottom of the header are not strictly necessary, so the header could be written as:

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

 

It is possible to add additional tags, although they will not be checked or enforced by StyleCop:

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

// <author>John Doe</author>

//-----------------------------------------------------------------------

SA1634: FileHeaderMustShowCopyright

文件頭部注釋必須顯示版權信息標識

//-----------------------------------------------------------------------

// <Tag>A file header which does not contain a copyright tag</Tag>

//-----------------------------------------------------------------------

 

A file header should include a copyright tag, as follows:

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

SA1635: FileHeaderMustHaveCopyrightText

文件頭部注釋必須有版權信息表示內容

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

// </copyright>

//-----------------------------------------------------------------------

 

A file header should include copyright text, as follows:

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

SA1636: FileHeaderMustContainFileName

文件頭部注釋必須包含文件名

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="My Company">

//     Custom company copyright tag.

// </copyright>

//-----------------------------------------------------------------------

SA1637: FileHeaderMustContainFileName

文件頭部注釋必須包含文件名

//-----------------------------------------------------------------------

// <copyright company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

 

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

SA1638: FileHeaderFileNameDocumentationMustMatchFileName

文件頭部注釋文件名注釋必須與文件名對應

//-----------------------------------------------------------------------

// <copyright file="File2.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

 

A violation of this rule would occur, since the file tag does not contain the name of the file. The header should be written as:

//-----------------------------------------------------------------------

// <copyright file="File1.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

SA1639: FileHeaderMustHaveSummary

文件頭部注釋不許有摘要

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

 

If this rule is enabled, the file header should contain a summary tag. For example:

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

// <summary>Defines the Widget class.</summary>

//-----------------------------------------------------------------------

SA1640: FileHeaderMustHaveValidCompanyText

文件頭部注釋必須有正確的公司信息

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="Sprocket Enterprises">

//     Copyright (c) Sprocket Enterprises. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

SA1641: FileHeaderCompanyNameTextMustMatch

文件頭部注釋公司內容必須對應

//-----------------------------------------------------------------------

// <copyright file="Widget.cs" company="My Company">

//     Custom company copyright tag.

// </copyright>

//-----------------------------------------------------------------------

SA1642: ConstructorSummaryDocumentationMustBeginWithStandardText

構造器的Summary注釋必須由標准內容開始

(參考幫助文檔)

SA1643: DestructorSummaryDocumentationMustBeginWithStandardText

析構器的Summary注釋必須由標准內容開始

    /// <summary>

    /// Initializes a new instance of the <see cref="Customer`1"/> class.

    /// </summary>

    public Customer()

    {

    }

 

    /// <summary>

    /// Initializes a new instance of the <see cref="Customer{T}"/> class.

    /// </summary>

    public Customer()

    {

    }

SA1644: DocumentationHeadersMustNotContainBlankLines

注釋頭部不能包含空白行

    /// <summary>

    /// <para>

    /// Joins a first name and a last name together into a single string.

    /// </para><para>

    /// Uses a simple form of string concatenation.

    /// </para>

    /// </summary>

    /// <param name="firstName">The first name to join.</param>

    /// <param name="lastName">The last name to join.</param>

    /// <returns>The joined names.</returns>

    public string JoinNames(string firstName, string lastName)

    {

        return firstName + " " + lastName;

    }

SA1645: IncludedDocumentationFileDoesNotExist

導入的文檔注釋文件不存在

    ///<include file="IncludedDocumentation.xml" path="root/EnabledMethodDocs" />

    public bool Enabled(bool true)

    {

    }

 

SA1646: IncludedDocumentationXPathDoesNotExist

導入的文檔注釋的XPath不存在

    ///<include file="IncludedDocumentation.xml" path="root/EnabledMethodDocs" />

    public bool Enabled(bool true)

    {

    }

SA1647: IncludeNodeDoesNotContainValidFileAndPath

導入的結點不存在正確的文件和路徑

    ///<include file="IncludedDocumentation.xml" path="root/EnabledMethodDocs" />

    public bool Enabled(bool true)

    {

    }

 

8.4 布局規則(LayoutRules)

標識及提示

中文及示例

是否檢查

SA1500: CurlyBracketsForMultiLineStatementsMustNotShareLine

當多行代碼使用{}時"{" 與 "}"必須單獨占一行

SA1501: StatementMustNotBeOnSingleLine

{}不能與代碼寫在同一行

SA1502: ElementMustNotBeOnSingleLine

元素定義不能在同一行

SA1503: CurlyBracketsMustNotBeOmitted

{}符號不能被省略

SA1504: AllAccessorMustBeMultiLineOrSingleLine

所有的訪問器代碼,必須是多行或一行(不能Get多行,Set單行)

SA1505: OpeningCurlyBracketsMustNotBeFollowedByBlankLine

{ 符號下面不能跟空行

SA1506: ElementDocumentationHeadersMustNotBeFollowedByBlankLine

元素注釋頭部不能跟空行

SA1507: CodeMustNotContainMultipleBlankLinesInARow

代碼不能包含連續的多個空行

SA1508: ClosingCurlyBracketsMustNotBePrecededByBlankLine

} 符號上方不能有空行

SA1509: OpeningCurlyBracketsMustNotBePrecedededByBlankLine

{ 符號與代碼之間不能有空行

SA1510: ChainedStatementBlocksMustNotBePrecededByBlankLine

使用 {} 符號並且連接的代碼之間不能有空行

SA1511: WhileDoFooterMustNotBePrecededByBlankLine

Do While代碼之間不能有空行

SA1512: SingleLineCommentsMustNotBeFollowedByBlankLine

單行注釋與代碼之間不能有空行

SA1513: ClosingCurlyBracketMustBeFollowedByBlankLine

} 符號后面必須有空行

SA1514: ElementDocumentationHeaderMustBePrecededByBlankLine

元素注釋頭部必須加空行

SA1515: SingleLineCommentMustBePrecededByBlankLine

單行注釋前面必須加空行

SA1516: ElementsMustBeSeparatedByBlankLine

元素必須用空行分隔

 

8.5 可維護性規則(Maintanability Rules)”

標識及提示

中文及示例

是否檢查

SA1300: ElementMustBeginWithUpperCaseLetter

元素必須首字母大寫

SA1301: ElementMustBeginWithLowerCaseLetter

元素必須首字母小寫

SA1302: InterfaceNamesMustBeginWithI

命名接口必須以I開頭

SA1303: ConstFieldNamesMustBeginWithUpperCaseLetter

常量字段命名必須首字母大寫

SA1304: NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter

非私有只讀字段必須首字母大寫

SA1305: FieldNamesMustNotUseHungarianNotation

字段名不能使用匈牙利命名法

SA1306: FieldNamesMustBeginWithLowerCaseLetter

字段名必須首字母小寫

SA1307: AccessibleFieldsMustBeginWithUpperCaseLetter

可訪問字段必須首字母大寫

SA1308: VariableNamesMustNotBePrefixed

變量名不能加前綴

SA1309: FieldNamesMustNotBeginWithUnderscore

字段名不能以"_"開頭

SA1310: FieldNamesMustNotContainUnderscore

字段名不能包含"_"

 

 

 

 

第九章 代碼分析

 

 

使用Visual Studio自身的代碼分析功能,檢查內容如下表,分為

 

1.安全規則。

2.互操作性規則

3.可維護性規則

4.可以只性規則

5.命名規則

6.全球化規則

7.設計規則

8.性能規則

9.移動性規則

10.用法規則

 

其中“是否檢查”一項中為“√”的內容不能違反。需在Visual Studio中設置為錯誤

 

 

 

9.1.安全性規則

標識

詳細信息

是否檢查

CA2100

檢查Sql查詢中是否有安全漏洞

CA2104

不要聲明只讀可變引用類型

CA2105

數組字段不應為只讀

CA2121

靜態構造函數應為私有

 

 

 

9.2.可靠性規則

標識

詳細信息

是否檢查

CA2000

超出范圍前釋放對象

9.3.可維護性規則

標識

詳細信息

是否檢查

CA1500

變量名不應與字段名相同

CA1501

避免過度繼承

CA1502

避免過度復雜

9.4.命名規則

標識

詳細信息

是否檢查

CA1700

不要將枚舉值命名為“Reserved”

CA1705

較長的首字母縮略詞應采用Pascal大小寫格式。

CA1706

較短的首字母縮略詞應全部大寫

CA1707

標識符不應包含下划線

CA1709

標識符的大小寫應該正確

CA1710

標識符應具有正確的后綴

CA1711

標識符應采用正確的后綴

CA1712

不要將類型名用作枚舉值的前綴

CA1713

事件不應具有 before 或 after 前綴

CA1715

標識符應具有正確的前綴

CA1716

標識符不應與關鍵字沖突

CA1718

避免在參數中使用特定於語言的類型名

CA1719

參數名不應與成員名沖突

CA1720

標識符不應包含類型名

CA1721

屬性名不應與 get 方法沖突

CA1722

標識符應采用正確的前綴

CA1724

類型名不應與命名空間沖突

CA1725

參數名應與基方法中的聲明保持一致

9.5.性能規則

標識

詳細信息

是否檢查

CA1800

避免進行不必要的強制轉換

CA1804

移除未使用的局部變量

CA1805

避免進行不必要的初始化

CA1809

避免過多的局部變量

CA1812

避免未實例化的內部類

CA1813

避免未密封的屬性

CA1819

屬性不應返回數組

CA1823

避免未使用的私有字段

9.6.用法規則

標識

詳細信息

是否檢查

CA1801

檢查未使用的參數

CA2202

不要多次釋放對象

CA2211

非常數字段不應該是可見的

CA2218

重寫 Equals 時重寫 GetHashCode

CA2219

不要在異常子句中引發異常

CA2222

不要降低繼承成員的可見性

CA2230

對個數可變的參數使用 params

CA2233

運算不應溢出

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM