StyleCop 和 StyleCop Analyzers

  • 1260
  • 0

StyleCop 搭配 Nuget 套件  StyleCop Analyzers 撰寫程式碼規範

StyleCop 和 StyleCop Analyzers

[目錄]

  1. 規則清單
    1. 拼寫規則 (Spacing Rules SA1000-)
    2. 可讀性規則 (Readability Rules SA1100-)
    3. 排序規則 (Ordering Rules SA1200-)
    4. 命名規則 (Naming Rules SA1300-)
    5. 可維護規則 (Maintainability Rules SA1400-)
    6. 排版規則 (Layout Rules SA1500-)
    7. 文件規則 (Documentation Rules SA1600-)
    8. 不清楚的規則內容
    9. StyleCop Analyzers 新增的規則
  2. 參考來源

[規則清單]

拼寫規則

  1. SA1000:KeywordsMustBeSpacedCorrectly: 關鍵字後需要正確的分隔

    • 一個空格 不可以有空格
      await, case, catch, fixed, for, foreach, from, group, if, in, into, join, let, lock, orderby, out, ref, return, select, stackalloc, switch, using, var, where, while, yield checked, default, sizeof, typeof, unchecked
    • 正確:

      switch (switchCondition)
      {
          case 1:
              break;
          default:
              break;
      }
      
    • 錯誤:

       switch(switchCondition)
       {
           case 1:
               break;
           default:
               break;
       }
      
  2. SA1001:CommasMustBeSpacedCorrectly: 逗號需要正確分隔

    • 正確:

      var array = new int[3] {1, 2, 3};
      
    • 錯誤:

      var array = new int[3] {1,2,3};
      
  3. SA1002:SemicolonsMustBeSpacedCorrectly: 分號需要正確分隔

    • 正確:

      var str = string.Empty;
      
    • 錯誤:

      var str = string.Empty ;
      
  4. SA1003:SymbolsMustBeSpacedCorrectly: 邏輯符號與元素之間需要空一格

    • 例外: 以 ! 表示否定句的情況
  5. SA1004:DocumentationLinesMustBeginWithSingleSpace: Function 說明註釋「///」後需要空一格

  6. SA1005:SingleLineCommentsMustBeginWithSingleSpace: 單行註釋「//」後需要空一格

  7. SA1006:PreprocessorKeywordsMustNotBePrecededBySpace: 預處理關鍵字內部不允許出現空格

    • 正確:

      #if Debug
      
    • 錯誤:

      # if Debug
      
  8. SA1007:OperatorKeywordMustBeFollowedBySpace: 操作必須要在一個空格之後

    • 正確:

      public MyClass operator +(MyClass a, MyClass b)
      {
      } 
      
    • 錯誤:

      public MyClass operator+(MyClass a, MyClass b)
      {
      } 
      
  9. SA1008:OpeningParenthesisMustBeSpacedCorrectly: 開始括號「(」前後不需要有空格

  10. SA1009:ClosingParenthesisMustBeSpacedCorrectly: 結束括號「)」前後不需要有空格

  11. SA1010:OpeningSquareBracketsMustBeSpacedCorrectly: 開始中括號「[」前後不需要有空格

  12. SA1011:ClosingSquareBracketsMustBeSpacedCorrectly: 結束中括號「]」前後不需要有空格

  13. SA1012:OpeningCurlyBracketsMustBeSpacedCorrectly: 開始大括號「{」前需要有一個空格或者是換行開始

  14. SA1013:ClosingCurlyBracketsMustBeSpacedCorrectly: 結束大括號「}」前需要有一個空格或者是單獨一行

  15. SA1014:OpeningGenericBracketsMustBeSpacedCorrectly: 同上

    • 不清楚發生的情況
  16. SA1015:ClosingGenericBracketsMustBeSpacedCorrectly: 同上

    • 不清楚發生的情況
  17. SA1016:OpeningAttributeBracketsMustBeSpacedCorrectly: 屬性開始括號「[」前後不需要有空格

  18. SA1017:ClosingAttributeBracketsMustBeSpacedCorrectly: 屬性結束括號「]」前後不需要有空格

  19. SA1018:NullableTypeSymbolsMustNotBePrecededBySpace: 空類型前不放置空格

    • 不清楚發生的情況
  20. SA1019:MemberAccessSymbolsMustBeSpacedCorrectly: 成員訪問關鍵字前後有空格

    • 不清楚發生的情況
  21. SA1020:IncrementDecrementSymbolsMustBeSpacedCorrectly: 自增、自減關鍵字要有空格

    • 不清楚發生的情況
  22. SA1021:NegativeSignsMustBeSpacedCorrectly: 負號不加空格

  23. SA1022:PositiveSignsMustBeSpacedCorrectly: 正號不加空格

  24. SA1023:DereferenceAndAccessOfMustBeSpacedCorrectly

    • 不清楚發生的情況
  25. SA1024:ColonsMustBeSpacedCorrectly: 冒號運算符號不加空格

    • Visual Studio 自動排版會將空格去掉

    • 正確:

      switch (num){
          case 1:
              break;
          default:
              break;
      }
      
    • 錯誤:

      switch (num){
          case 1 :
              break;
          default :
              break;
      }
      
  26. SA1025:CodeMustNotContainMultipleWhitespaceInARow: 同一行內不允許出現多個連續空格

    • Visual Studio 自動排版會將連續空格去掉

    • 正確:

      var str = "A" + "B";
      
    • 錯誤:

      var str = "A"       +     "B"      ;
      
  27. SA1026:CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation: new array 後的 new 關鍵字不能有空格

    • Visual Studio 自動排版不會有空格

    • 正確:

      var a = new[] {1, 2, 3};
      
    • 錯誤:

      var a = new [] {1, 2, 3};
      
  28. SA1027:TabsMustNotBeUsed: 不使用 Tab 空格

    • Visual Studio 預設將 Tab 換成 4 格空白鍵
  29. SA1028CodeMustNotContainTrailingWhitespace: 每一行的結尾不可以是空白

可讀性規則

  1. SA1100:DoNotPrefixCallsWithBaseUnlessLocalImplementationExists: 使用「this.」取代「base.」

  2. SA1101:PrefixLocalCallsWithThis: 「this.」前綴不能省略

    • Visual Studio 預設建議省略,需要一併修改「IDE0003」規則,將「IDE0003」設定成和此規則相反
  3. SA1102:QueryClauseMustFollowPreviousClause: LINQ 語句行與行之間不可有多餘的空行

    • 正確:

      var query = from str in array
                  select str;
      
    • 錯誤:

      var query = from str in array
                  
                  select str;
      
  4. SA1103:QueryClausesMustBeOnSeparateLinesOrAllOnOneLine: LINQ 語句若要分行則是每一個關鍵字一行,否則應該都在同一行

    • 若已有換行 Visual Studio 預設全部換行

    • 正確:

        var query = from str in array 
                where str == "a"
                select str;
      
      
        var query = from str in array where str == "a" select str;
      
    • 錯誤:

      var query = from str in array where str == "a"
                    
          select str;
      
  5. SA1104:QueryClauseMustBeginOnNewLineWhenPreviousClauseSpansMultipleLines: LINQ 語句的關鍵字要從新的一行開始

    • Visual Studio 預設排版就會換行

    • 正確:

      from element in this.GetElements(
         12,
         1)  
      select element;
      
    • 錯誤:

      from element in this.GetElements(
         12,
         45) select element;
      
  6. SA1105:QueryClausesSpanningMultipleLinesMustBeginOnOwnLine: LINQ 語句換行時,需要連關鍵字一起換行,不能關鍵字留在上一行

    • Visual Studio 預設排版就會換行

    • 正確:

      from element in models 
      select 
      element.Name;
      
    • 錯誤:

      from element in models select 
      element.Name;
      
  7. SA1106:CodeMustNotContainEmptyStatements: 不允許有多餘的分號

  8. SA1107:CodeMustNotContainMultipleStatementsOnOneLine: 同一行裡不允許出現多個宣告句

  9. SA1108:BlockStatementsMustNotContainEmbeddedComments: 註解不能放在宣告句和開始括號之間

    • 正確:

      // Make sure x does not equal y
      if (x != y)
      {
      }
      
    • 錯誤:

      if (x != y)
      // Make sure x does not equal y
      {
      }
      
  10. SA1109:BlockStatementsMustNotContainEmbeddedRegions: 「#region」不能放在聲明語句和開始括號之間

  11. SA1110:OpeningParenthesisMustBeOnDeclarationLine Method 開始括號「(」不可以單獨一行,需要放在呼叫方法的那一行

    • 正確:

      this.Getstring(
        "a", "b");
      
    • 錯誤:

      this.Getstring
      (
        "a", "b");
      
  12. SA1111:ClosingParenthesisMustBeOnLineOfLastParameter: Method 結束括號「)」與最後一個参數同行

    • 正確:

      this.Getstring(
        "a", "b");
      
    • 錯誤:

      this.Getstring(
        "a", "b"
      );
      
  13. SA1112:ClosingParenthesisMustBeOnLineOfOpeningParenthesis: Method 為空參數時,結束括號不可換行

    • 正確:

      public string GetName( )
      {
        return "Name";
      }
      
    • 錯誤:

      public string GetName(
            )
      {
        return "Name";
      }
      
  14. SA1113:CommaMustBeOnSameLineAsPreviousParameter: Method 參數以逗號分隔時,逗號必須在前一個參數的行尾

    • 正確:

      var result = GetElements(
        1, 
        2);
      
    • 錯誤:

      var result = GetElements(
        1
        , 2);
      
  15. SA1114:ParameterListMustFollowDeclaration: Method 參數和 Method 中間不能有空白行

    • 正確:

      public string GetElements(
            int a, int b)
        {
            return a.ToString();
        }
      
    • 錯誤:

      public string GetElements(
      
            int a, int b)
        {
            return a.ToString();
        }
      
  16. SA1115:ParameterMustFollowComma: Method 参數與参數之間不能隔空白行

  17. SA1116:SplitParametersMustStartOnLineAfterDeclaration: Method 所有參數在同一行或從下一行開始一行一個參數

  18. SA1117:ParametersMustBeOnSameLineOrSeparateLines: Method 所有參數在同一行或全部在新的一行或一行一個參數,參數不要有的同行有的不同行

    • 正確:

      public int GetMaxNum(
        int a, int b, int c)
      {
          return Math.Max(Math.Max(a, b), c);
      }
      
      public int GetMaxNum(
        int a,
        int b,
        int c)
      {
          return Math.Max(Math.Max(a, b), c);
      }
      
    • 錯誤:

      public int GetMaxNum(int a,
            int b, int c)
      {
          return Math.Max(Math.Max(a, b), c);
      }
      
  19. SA1118:ParameterMustNotSpanMultipleLines: Method 使用時,同一参數要放在同一行,不要換行

    • 正確:

      var merged = Getstring(
                    "No",
                    "FirstName" + "LastName");
      
    • 錯誤:

      var merged = Getstring(
                    "No",
                    "FirstName" +
                    "LastName");
      
  20. SA1119:StatementMustNotUseUnnecessaryParenthesis: 去除不必要的括弧

  21. SA1120:CommentsMustContainText: 註解不得為空白

  22. SA1121:UseBuiltInTypeAlias: 使用預設的類型別名

    Type Alias Type Fully Qualified Type
    bool Boolean System.Boolean
    byte Byte System.Byte
    char Char System.Char
    decimal Decimal System.Decimal
    double Double System.Double
    short Int16 System.Int16
    int Int32 System.Int32
    long Int64 System.Int64
    object Object System.Object
    sbyte SByte System.SByte
    float Single System.Single
    string String System.String
    ushort UInt16 System.UInt16
    uint UInt32 System.UInt32
    ulong UInt64 System.UInt64
  23. SA1122:UseStringEmptyForEmptyStrings: 使用 String.Empty 取代 “” 空字串

  24. SA1123:DoNotPlaceRegionsWithinElements: 在 Function 內不使用「#region」

  25. SA1124:DoNotUseRegions: 不使用「#region」

  26. SA1125:UseShorthandForNullableTypes: 使用簡寫版的可為 null 類型

    • 如: 「int?」
  27. SA1126:PrefixCallsCorrectly: 調用類成員的時候要帶上「this」前綴

  28. SA1127:GenericTypeConstraintsMustBeOnOwnLine: 泛型條件約束應該要多行顯示,不可以放在同一行

  29. SA1128:ConstructorInitializerMustBeOnOwnLine: 建構函式初始化繼承時不可以放在同一行,應該要換新的一行,並以「:」開頭

  30. SA1129:DoNotUseDefaultValueTypeConstructor:

    • 不清楚發生的情況
  31. SA1130:UseLambdaSyntax: delegate 委派的匿名方法使用 Lambda 語法 (=>)

    • 正確:
      Action a = () => { x = 0; };
      Action b = () => { y = 0; };
      Func<int, int, int> c = (m, n) => m + n;
    
    • 錯誤:
      Action a = delegate { x = 0; };
      Action b = delegate() { y = 0; };
      Func<int, int, int> c = delegate(int m, int n) { return m + n; };
    
  32. SA1131:UseReadableConditions: 變數不可以出現在條件句右邊

    • 正確:
         public void Method(string value)
         {
             if (value == null)
             {
                 throw new ArgumentNullException(nameof(value));
             }
         }
        
    • 錯誤:
     public void Method(string value)
     {
         if (null == value) // SA1131
         {
             throw new ArgumentNullException(nameof(value));
         }
     }
    
  33. SA1132:DoNotCombineFields: 不要串聯欄位宣告

    • 正確:

      public class TypeName
      {
          private int field1;
          private int field2;
      }
      
    • 錯誤:

      public class TypeName
      {
          private int field1,
              field2; // SA1132
      }
      
  34. SA1133:DoNotCombineAttributes: 一個中括號只宣告一個屬性

    • 正確:

      [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MyCodeFixProvider))]
      [Shared]
      public class MyCodeFixProvider : CodeFixProvider
      {
      }
      
    • 錯誤:

      [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MyCodeFixProvider)), Shared]
      public class MyCodeFixProvider : CodeFixProvider
      {
      }
      
  35. SA1134:AttributesMustNotShareLine: 不要在同一行宣告多個屬性

    • 正確:

      [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MyCodeFixProvider))]
      [Shared]
      public class MyCodeFixProvider : CodeFixProvider
      {
      }
      
    • 錯誤:

      [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MyCodeFixProvider))][Shared]
      public class MyCodeFixProvider : CodeFixProvider
      {
      }
      

排序規則

  1. SA1200:UsingDirectivesMustBePlacedWithinNamespace: using 部分必須在 Namespace 內部

    • 和 Visual Stduio 新文件不同,此選項除了這裡的設定外,還可以透過 Configuration 檔案設定
  2. SA1201:ElementsMustAppearInTheCorrectOrder: 所有的元素按照規定的出現順序依序顯示

    • 在最一開始的情況應按照以下順序:
      • Extern Alias Directives
      • Using Directives
      • Namespaces
      • Delegates
      • Enums
      • Interfaces
      • Structs
      • Classes
    • 在 Interfaces、Structs、Classes 內的元素依照以下順序:
      • Fields
      • Constructors
      • Finalizers (Destructors)
      • Delegates
      • Events
      • Enums
      • Interfaces
      • Properties
      • Indexers
      • Methods
      • Structs
      • Classes*
    • 在實現介面時,若是需要將成員分組時則可以再建立一個 Partial 類別處理並寫在同一份文件內
  3. SA1202:ElementsMustBeOrderedByAccess: 元素的修飾詞按照規定的出現順序依序顯示

    • public
    • internal
    • protected internal
    • protected
    • private
  4. SA1203:ConstantsMustAppearBeforeFields: 常數擺放在其它欄位之前

  5. SA1204:StaticElementsMustAppearBeforeInstanceElements Static: Static 元素擺放在非靜態元素前面

  6. SA1205:PartialElementsMustDeclareAccess: Partial 元素必須宣告讀寫權限修飾詞

    • 和 Visual Studio 的 ID0040 相同
  7. SA1206:DeclarationKeywordsMustFollowOrder: 讀寫權限修飾詞按照規定的出現順序依序顯示

    • 和 Visual Studio 的 CS0267 相同
    • 依照以下順序排序
      • Access modifiers
      • static
      • All other keywords
  8. SA1207:ProtectedMustComeBeforeInternal: 宣告時 Protected 寫在 Internal 之前

    • 參考 SA1202 規則

    • 正確:

      protected internal int Methid()
      {
          return 1;
      }
      
    • 錯誤:

      internal protected int Methid()
      {
          return 1;
      }
      
  9. SA1208:SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives: using System 需要在其他的 using 之前

    • 正確:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      using Newtonsoft.Json;
      
    • 錯誤:

      using Newtonsoft.Json;
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      
  10. SA1209:UsingAliasDirectivesMustBePlacedAfterOtherUsingDirectives: using 部分起別名的排在最後面

    • 正確:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web.Mvc;
      using Newtonsoft.Json;
      using Q = QRCoder;
      
    • 錯誤:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web.Mvc;
      using Q = QRCoder;
      using Newtonsoft.Json;
      
  11. SA1210:UsingDirectivesMustBeOrderedAlphabeticallyByNamespace: using 部分按照字母順序排序

  12. SA1211:UsingAliasDirectivesMustBeOrderedAlphabeticallyByAliasName: using 有別名的按照別名的字母順序排序

  13. SA1212:PropertyAccessorsMustFollowOrder: 屬性先 get 再 set

  14. SA1213:EventAccessorsMustFollowOrder: 屬性增減時應該先增加再刪除

    • 正確:

      public event EventHandler NameChanged
      {
        add { this.nameChanged += value; }
        remove { this.nameChanged -= value; }
      }
      
    • 錯誤:

      public event EventHandler NameChanged
      {
        remove { this.nameChanged -= value; }
        add { this.nameChanged += value; }
      }
      
  15. SA1214:StaticReadonlyElementsMustAppearBeforeStaticNonReadonlyElements: Static Readonly 元素在 Static NonReadonly 元素之前

    • 正確:

      public readonly string Readonly = "No";
      public string Notreadonly = "No";
      
    • 錯誤:

      public string Notreadonly = "No";
      public readonly string Readonly = "No";
      
  16. SA1215:InstanceReadonlyElementsMustAppearBeforeInstanceNonReadonlyElements: 一個readonly 實例元素要在一個非readonly 實例元素

  17. SA1216:UsingStaticDirectivesMustBePlacedAtTheCorrectLocation: using static 時應擺在一般的 using 之後和別名 using 之前

    • 正確:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using QRCoder;
      using static Newtonsoft.Json.JsonConvert;
      using MVC = System.Web.Mvc;
      
    • 錯誤:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using QRCoder;
      using MVC = System.Web.Mvc;
      using static Newtonsoft.Json.JsonConvert;
      
  18. SA1217:UsingStaticDirectivesMustBeOrderedAlphabetically: using static 時應按照字母順序排序

命名規則

  1. SA1300:ElementMustBeginWithUpperCaseLetter: 以下元素首字母必須大寫

    • Namespaces
    • Classes
    • Enums
    • Enum members
    • Structs
    • Delegates
    • Events
    • Methods
    • Properties
  2. SA1302:InterfaceNamesMustBeginWithI: Interface 必須以「I」開頭

    • 和 Visual Studio 的 IDE1006 相同
  3. SA1303:ConstFieldNamesMustBeginWithUpperCaseLetter: Const 常數首字母大寫

  4. SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter: 非私有、非唯讀的欄位必須首字母大寫

  5. SA1305:FieldNamesMustNotUseHungarianNotation: 除了 configuration 列表的前輟詞外不可以出現匈牙利命名規則

    • StyleCop Analyzers 預設關閉
  6. SA1306:FieldNamesMustBeginWithLowerCaseLetter: 私有欄位的變數名稱首字母小寫

    • 此規則和原有的 StyleCop 不同

    • 原有的 StyleCop 檢驗

      • fields
      • parameters
      • local variables
    • 此處檢驗

      • fields
    • 正確:

      private string test = string.Empty;
      
    • 錯誤:

      private string Test = string.Empty;
      
  7. SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter: public 或 internal 變數首字母大寫

    • 正確:

      public string Test = string.Empty;
      
    • 錯誤:

      public string test = string.Empty;
      
  8. SA1308:VariableNamesMustNotBePrefixed: 變數名稱不能有前綴

    • 限定不能以「m_ 」、「s_ 」開頭
  9. SA1309:FieldNamesMustNotBeginWithUnderscore: 欄位不能以底線開頭

    • 正確:

      private string test = string.Empty;
      
    • 錯誤:

      private string _test = string.Empty;
      
  10. SA1310:FieldNamesMustNotContainUnderscore: 欄位不能包含底線

    • 使用駝峰式命名

    • 正確:

      private string testResult = string.Empty;
      
    • 錯誤:

      private string test_result = string.Empty;
      
  11. SA1311:StaticReadonlyFieldsMustBeginWithUpperCaseLetterl: static readonly欄位首字母大寫

    • 正確:

      private static readonly string TestResult = string.Empty;
      
    • 錯誤:

      private static readonly string testResult = string.Empty;
      
  12. SA1312:VariableNamesMustBeginWithLowerCaseLetter: 變數名稱首字母小寫

  13. SA1313:ParameterNamesMustBeginWithLowerCaseLetter: 參數名稱首字母小寫

可維護規則

  1. SA1400:AccessModifierMustBeDeclared: 元素必須定義讀寫權限修飾詞

    • 正確:

      private string test = string.Empty;
      
    • 錯誤:

      string test = string.Empty;
      
  2. SA1401:FieldsMustBePrivate: 欄位必須為 private 修飾詞,不應該開放直接存取,建議透過 Method 存取

    • 正確:

      public class MyClass
      {
        private int counts;
      
        public int GetCounts()
        {
            return counts;
        }
      
        public void SetCounts(int value)
        {
            counts = value;
        }
      }
      
    • 錯誤:

      public class MyClass
      {
        public int counts;
      }
      
  3. SA1402:FileMayOnlyContainASingleClass 一個 CS 檔案裡只定義一個 Class

  4. SA1403:FileMayOnlyContainASingleNamespace: 一個 CS 檔案只包含一個 Namespace

  5. SA1404:CodeAnalysisSuppressionMustHaveJustification: Suppression 取消規則時,需要包含理由 (Justification)

  6. SA1405:DebugAssertMustProvideMessageText: 使用 Debug.Assert 需要包括訊息內容

    • 正確:

      Debug.Assert(value != true, "The value must always be true.");
      
    • 錯誤:

      Debug.Assert(value != true);
      
  7. SA1406:DebugFailMustProvideMessageText: 使用 Debug.Assert 需要包括訊息內容

    • 正確:

      Debug.Fail("The value must always be true.");
      
    • 錯誤:

      Debug.Fail();
      
  8. SA1407:ArithmeticExpressionsMustDeclarePrecedence: 複雜算數操作時需要用括號明確指出計算順序

    • 和 Visual Studio 的 IDE0047 衝突

    • 正確:

      int x = 5 + (y * ((b / 6) % z)) - 2;
      
    • 錯誤:

      int x = 5 + (y * (b / 6 % z)) - 2;
      
  9. SA1408:ConditionalExpressionsMustDeclarePrecedence: 複雜條件表達式需要用括號明確指出優先順序

    • 正確:

      if (x || (y && z && a) || b)
      
    • 錯誤:

      if (x || y && z && a || b)
      

10. SA1409:RemoveUnnecessaryCode: 移除無用的代碼

  1. SA1410:RemoveDelegateParenthesisWhenPossible: 使用 C 匿名方法空参數時,不要包括空括號

    • 正確:

      this.Method(delegate { return 2; });
      
    • 錯誤:

      this.Method(delegate() { return 2; });
      
  2. SA1411:AttributeConstructorMustNotUseUnnecessaryParenthesis: 使用屬性構造函數空参數時,不要包括空括號

    • 正確:

      [Serializable]
      
    • 錯誤:

      [Serializable()]
      
  3. SA1412:StoreFilesAsUtf8: 檔案儲存時,儲存成 utf-8 格式

排版規則

  1. SA1500:CurlyBracketsForMultiLineStatementsMustNotShareLine: 大括號「{}」在宣告句或元素時需要單獨一行

    • 正確:

      public string GetStr()
      {
        return "str";
      }
      
    • 錯誤:

      public string GetStr() {
        return "str";
      }
      
      public string GetStr() 
      {
        return "str"; }
      
  2. SA1501:StatementMustNotBeOnASingleLine: 當陳述句包含大括弧「{}」時不能放在同一行

    • 正確:

      public object Method()
      {
          lock (this) 
          {
              return this.value; 
          }
      }
      
    • 錯誤:

      public object Method()
      {
          lock (this) { return this.value; }
      }
      
  3. SA1502:ElementMustNotBeOnASingleLine: 當元素包含大括弧「{}」時不能放在同一行

    • 正確:

      public void Method()
      {
      }
      
    • 錯誤:

      public void Method() { }
      
  4. SA1503:CurlyBracketsMustNotBeOmitted: 大括弧「{}」在單行程式碼的情況下不能省略

    • 正確:

      if (true) 
      {
        return this.value;  
      }
      
    • 錯誤:

      if (true) 
        return this.value;
      
  5. SA1504:AllAccessorsMustBeSingleLineOrMultiLine: 屬性的 Set、Get 採取各一行書寫或全部換行

    • 正確:

      public bool Enabled
      {
        get { return this.enabled; }
        set { this.enabled = value; }
      }
      
      public bool Enabled
      {
          get 
          { 
              return this.enabled; 
          }
      
          set 
          { 
              this.enabled = value;
          }
      }
      
    • 錯誤:

      public bool Enabled
      {
          get { return this.enabled; }
      
          set
          {
              this.enabled = value;
          }
      }
      
  6. SA1505:OpeningCurlyBracketsMustNotBeFollowedByBlankLine: 開始大括號「{」後不能有空白行

    • 正確:

      public bool Enabled
      {
          get { return this.enabled; }
      }
      
    • 錯誤:

      public bool Enabled
      {
      
          get { return this.enabled; }
      }
      
  7. SA1506:ElementDocumentationHeadersMustNotBeFollowedByBlankLine: 元素說明註釋和宣告句中間不能有空白行

    • 正確:

      /// <summary>
      /// Gets a value indicating whether the control is enabled.
      /// </summary>
      public bool Enabled
      {
          get { return this.enabled; }
      }
      
    • 錯誤:

      /// <summary>
      /// Gets a value indicating whether the control is enabled.
      /// </summary>
      
      public bool Enabled
      {
          get { return this.enabled; }
      }
      
  8. SA1507:CodeMustNotContainMultipleBlankLinesInARow: 不允許有連續多個空白行

    • 正確:

      public object Method()
      {
          lock (this) 
          {
              var str = string.Empty;
              return this.value; 
          }
      }
      
    • 錯誤:

      public object Method()
      {
          lock (this) 
          {
              var str = string.Empty;
              
              
              
              return this.value; 
            }
        }  
      
  9. SA1508:ClosingCurlyBracketsMustNotBePrecededByBlankLine: 結束大括號「}」之前不能有空白行

    • 正確:

      public bool Enabled
      {
          get { return this.enabled; }
      }
      
    • 錯誤:

      public bool Enabled
      {
          get { return this.enabled; }
      
      }
      
  10. SA1509:OpeningCurlyBracketsMustNotBePrecededByBlankLine: 開始大括號「{」之前不能有空白行

    • 正確:

      public bool Enabled
      {
          get { return this.enabled; }
      }
      
    • 錯誤:

      public bool Enabled
      
      {
          get { return this.enabled; }
      }
      
  11. SA1510:ChainedStatementBlocksMustNotBePrecededByBlankLine: 連續陳述句區塊之間不能有空白行

    • 正確:

      try
      {
          this.SomeMethod();
      }
      catch (Exception ex)
      {
          Console.WriteLine(ex.ToString());
      }
      
    • 錯誤:

      try
      {
          this.SomeMethod();
      }
      
      catch (Exception ex)
      {
          Console.WriteLine(ex.ToString());
      }
      
  12. SA1511:WhileDoFooterMustNotBePrecededByBlankLine: 與 SA1510 相同,Do 語句與 While 語句之間不能有空白行

  13. SA1512:SingleLineCommentsMustNotBeFollowedByBlankLine: 單一單行註解「//」後不能有空白行

    • 若為了註解語法,則請使用「////」使規則被忽略
  14. SA1513:ClosingCurlyBracketMustBeFollowedByBlankLine: 結束大括號「}」之後,若還有程式碼必須空一行

    • 正確:

      if (a == 1)
      {
          return a;
      }
      
      return 0;
      
    • 錯誤:

      if (a == 1)
      {
          return a;
      }
      return 0;
      
  15. SA1514:ElementDocumentationHeaderMustBePrecededByBlankLine: 元素說明註釋之前需要和前一個元素空一行

    • 正確:

      /// <summary>
      /// 說明1
      /// </summary>
      /// <returns>計數</returns>
      public int GetCounts()
      {
          return counts;
      }
      
      /// <summary>
      /// 說明2
      /// </summary>
      /// <param name="value">設定計數</param>
      public void SetCounts(int value)
      {
          counts = value;
      }
      
    • 錯誤:

      /// <summary>
      /// 說明1
      /// </summary>
      /// <returns>計數</returns>
      public int GetCounts()
      {
          return counts;
      }
      /// <summary>
      /// 說明2
      /// </summary>
      /// <param name="value">設定計數</param>
      public void SetCounts(int value)
      {
          counts = value;
      }
      
  16. SA1515:SingleLineCommentMustBePrecededByBlankLine: 單行註釋之前要有一個空白行

    • 不加空白行則是使用「////」註解 (不建議採用)

    • 正確:

        public bool Enabled
        {
            get
            {
                Console.WriteLine("Getting the enabled flag.");
                
                // Return the value of the 'enabled' field.
                return this.enabled;
            }
        }
      
    • 錯誤:

      public bool Enabled
      {
          get
          {
              Console.WriteLine("Getting the enabled flag.");
              // Return the value of the 'enabled' field.
              return this.enabled;
          }
      }
      
  17. SA1516:ElementsMustBeSeparatedByBlankLine: 兩個元素之間要有一個空白行

  18. SA1517:CodeMustNotContainBlankLinesAtStartOfFile: 在程式碼開始處 (行1) 不需要空白行

  19. SA1518:CodeMustNotContainBlankLinesAtEndOfFile: 在程式碼結束後不需要空白行

文件規則

  1. SA1600: ElementsMustBeDocumented: 元素必須有說明註釋

    • 包含以下元素
      • classes
      • constructors
      • delegates
      • enums
      • events
      • finalizers
      • indexers
      • interfaces
      • methods
      • properties
      • structs
    • Visual Studio 未如預期跳出警告
  2. SA1601: PartialElementsMustBeDocumented: Partial 修飾的成員必須有說明註釋

    • Visual Studio 未如預期跳出警告
  3. SA1602: EnumerationItemsMustBeDocumented 列舉型別必須添加註解

    • Visual Studio 未如預期跳出警告

    • 正確:

      /// <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
      }
      
    • 錯誤:

      /// <summary>
      /// Types of animals.
      /// </summary>
      public enum Animals
      {
          Dog,
          Cat,
          Horse
      }
      
  4. SA1603: DocumentationMustContainValidXml: 註解的關鍵字不能有錯字

    • StyleCop Analyzers 預設取消此規則
  5. SA1604: ElementDocumentationMustHaveSummary 元素註解必須包含 Summary 關鍵字

    • Visual Studio 未如預期跳出警告
  6. SA1605:PartialElementDocumentationMustHaveSummary: Partial 修飾的成員註解必須包含 Summary 關鍵字

    • Visual Studio 未如預期跳出警告
  7. SA1606:ElementDocumentationMustHaveSummaryText: Summary Tag 內不能空白

    • 正確:

      /// <summary> 
      /// Get Customer Data
      /// </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>  </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 ...
      }
      
  8. SA1607:PartialElementDocumentationMustHaveSummaryText: Partial 修飾的成員註解 <Summary> Tag 內不能空白

    • 和 SA1606 類似

    • 正確:

      /// <summary>
      /// Documentation for the second part of Class1.
      /// </summary>
      public partial class Class1
      {
      }
      
    • 錯誤:

      /// <summary>
      ///
      /// </summary>
      public partial class Class1
      {
      }
      
  9. SA1608:ElementDocumentationMustNotHaveDefaultSummary: <Summary> Tag 內不能使用預設的 Summary 值

    • 正確:

      /// <summary>
      /// Documentation for the second part of Class1.
      /// </summary>
      public partial class Class1
      {
      }
      
    • 錯誤:

      /// <summary>
      /// Summary description for the Class1 class.
      /// </summary>
      public partial class Class1
      {
      }
      
  10. SA1609:PropertyDocumentationMustHaveValue: 屬性的註解中必須包含 <Value> Tag

    • StyleCop Analyzers 預設關閉
  11. SA1610:PropertyDocumentationMustHaveValueText: 屬性的註解 <Value> Tag 不能為空白

    • Visual Studio 未如預期跳出警告
  12. 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;
      }
      
    • 錯誤:

      /// <summary>
      /// Joins a first name and a last name together into a single string.
      /// </summary>
      /// <returns>The joined names.</returns>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  13. SA1612:ElementParameterDocumentationMustMatchElementParameters: 說明註解內的參數個數要和實際參數相同

    • Visual Studio 未如預期跳出警告,但是當說明註釋內的數量 > 實際數量時會跳出錯誤

    • 正確:

      /// <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;
      }
      
    • 錯誤:

      /// <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>
      /// <param name="middleName">The middle name to join.</param>
      /// <returns>The joined names.</returns>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  14. SA1613:ElementParameterDocumentationMustDeclareParameterName: 說明註解內的參數必須有参數的名稱,name 屬性不能空白

    • 正確:

      /// <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;
      }
      
    • 錯誤:

      /// <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="">The last name to join.</param>
      /// <returns>The joined names.</returns>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  15. 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;
      }
      
    • 錯誤:

      /// <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"></param>
      /// <returns>The joined names.</returns>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  16. SA1615:ElementReturnValueMustBeDocumented: 說明註解必須包含回傳值的 <return> Tag

    • 正確:

      /// <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;
      }
      
    • 錯誤:

      /// <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>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  17. SA1616:ElementReturnValueDocumentationMustHaveText: 說明註解內的回傳值內容不得為空白

    • 正確:

      /// <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;
      }
      
    • 錯誤:

      /// <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></returns>
      public string JoinNames(string firstName, string lastName)
      {
          return firstName + " " + lastName;
      }
      
  18. SA1617:VoidReturnValueMustNotBeDocumented: 當 Method 沒有回傳值時,說明註釋不得包含 <return> Tag

    • 正確:

      /// <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>
      public void JoinNames(string firstName, string lastName)
      {
          var fullName = firstName + " " + lastName;
      }
      
    • 錯誤:

      /// <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 void JoinNames(string firstName, string lastName)
      {
          var fullName = firstName + " " + lastName;
      }
      
  19. 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>
      { 
      }
      
    • 錯誤:

      /// <summary>
      /// A sample generic class.
      /// </summary>
      public class Class1<S, T>
      { 
      }
      
  20. SA1619:GenericTypeParametersMustBeDocumentedPartialClass: SA1618 情況如果有 Partial 類存在都要有說明註解

  21. 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>
      { 
      }
      
    • 錯誤:

      /// <summary>
      /// A sample generic class.
      /// </summary>
      /// <typeparam name="S">The first generic type parameter.</typeparam>
      /// <typeparam name="T">The second generic type parameter.</typeparam>
      /// <typeparam name="U">The third generic type parameter.</typeparam>
      public class Class1<S, T>
      { 
      }
      
  22. SA1621:GenericTypeParameterDocumentationMustDeclareParameterName:說明註釋內泛型參數必須有参數的名稱,name 屬性不能空白

    • 正確:

      /// <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>
      { 
      }
      
    • 錯誤:

      /// <summary>
      /// A sample generic class.
      /// </summary>
      /// <typeparam name="S">The first generic type parameter.</typeparam>
      /// <typeparam name="">The second generic type parameter.</typeparam>
      public class Class1<S, T>
      { 
      }
      
  23. 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>
      { 
      }
      
    • 錯誤:

      /// <summary>
      /// A sample generic class.
      /// </summary>
      /// <typeparam name="S">The first generic type parameter.</typeparam>
      /// <typeparam name="T"></typeparam>
      public class Class1<S, T>
      { 
      }
      
  24. SA1623:PropertySummaryDocumentationMustMatchAccessors: 屬性的說明註解必須依照屬性的讀和寫情況分別以 Gets、Sets、Gets or sets 開頭

    • 但 set 屬性為 private 屬性時,則不在此限
  25. SA1624:PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess: 屬性的說明註解必須依照屬性的讀和寫情況分別以 Gets、Sets、Gets or sets 開頭

    • 但 set 屬性為 private 屬性時,則不在此限
  26. 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;
      }
      
    • 錯誤:

      /// <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)
      {
          return firstName + " " + lastName;
      }
      
  27. SA1626:SingleLineCommentsMustNotUseDocumentationStyleSlashes: 單行註解不能使用「///」說明註解,應該使用「//」形式

  28. SA1627:DocumentationTextMustNotBeEmpty: 說明註解每一個 Tag 內不得為空白

    • 和 SA1607、SA1610、SA1614、SA1616、SA1622 類似
  29. SA1628:DocumentationTextMustBeginWithACapitalLetter: 說明註解內部的描述必須以大寫字母開頭

    • StyleCop Analyzers 預設取消此規則
  30. SA1629:DocumentationTextMustEndWithAPeriod: 說明註解內部的描述必須以英文的句號結束

    • StyleCop Analyzers 預設取消此規則
  31. SA1630:DocumentationTextMustContainWhitespace:說明註解內部的描述各單字必須正確空格分隔

    • StyleCop Analyzers 預設取消此規則
  32. SA1631:DocumentationMustMeetCharacterPercentage 說明註解內部的描述不能包含過多的非文字、數字的符號

    • StyleCop Analyzers 預設取消此規則
  33. SA1632:DocumentationTextMustMeetMinimumCharacterLength: 已經作廢的規則,不允許有太短的字符串

  34. SA1633:FileMustHaveHeader: 程式碼文件開始處必須包含版權信息

    • StyleCop Analyzers 預設關閉
  35. SA1634:FileHeaderMustShowCopyright: 程式碼文件開始處的 Header comment 中必須包含 <coptyright> Tag

  36. SA1635:FileHeaderMustHaveCopyrightText: 程式碼文件開始處的 Header comment 中必須包含版權信息 Copyright ©

  37. SA1636:FileHeaderCopyrightTextMustMatch:程式碼文件開始處的 Header comment 的版權訊息需要和 configuration 內的設定相同

  38. SA1637:FileHeaderMustContainFileName: 程式碼文件開始處的 Header comment 必須包含文件名稱

  39. SA1638:FileHeaderFileNameDocumentationMustMatchFileName: 程式碼文件開始處的 Header comment 的文件名稱必須與實際的名稱相同

  40. SA1639:FileHeaderMustHaveSummary: 程式碼文件開始處的 Header comment 必須包含 <summary> Tag

    • StyleCop Analyzers 預設關閉
  41. SA1640:FileHeaderMustHaveValidCompanyText: 程式碼文件開始處的 Header comment 必須含公司名字

    • 正確:

      // <copyright file="HomeController.cs" company="PlaceholderCompany">
      // Copyright (c) PlaceholderCompany. All rights reserved.
      // </copyright>
      
    • 錯誤:

      // <copyright file="HomeController.cs">
      // Copyright (c) PlaceholderCompany. All rights reserved.
      // </copyright>
      
  42. SA1641:FileHeaderCompanyNameTextMustMatch: 程式碼文件開始處的 Header comment 的公司名稱需要和 configuration 內的設定相同

  43. SA1642:ConstructorSummaryDocumentationMustBeginWithStandardText: 建構子函式說明註解使用標準格式

    • 正確:

      /// <summary>
      /// Hello is Class1
      /// </summary>
      public class Class1
      {
          /// <summary>
          /// Initializes a new instance of the <see cref="Class1"/> class.
          /// </summary>
          public Class1()
          {
          }
      }
      
    • 錯誤:

      /// <summary>
      /// Hello is Class1
      /// </summary>
      public class Class1
      {
          /// <summary>
          /// Class1 初始化
          /// </summary>
          public Class1()
          {
          }
      }
      
  44. SA1643:DestructorSummaryDocumentationMustBeginWithStandardText: 解構函式說明註解使用標準格式

    • 正確:

      /// <summary>
      /// Finalizes an instance of the <see cref="Customer"/> class.
      /// </summary>
      ~Customer()
      {
      }
      
    • 錯誤:

      /// <summary>
      /// This is Finalizes class.
      /// </summary>
      ~Customer()
      {
      }
      
  45. SA1644:DocumentationHeadersMustNotContainBlankLines: 註解中不能出現空白行

    • StyleCop Analyzers 預設取消此規則

    • 正確:

      /// <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;
      }
      
    • 錯誤:

      /// <summary>
      /// Joins a first name and a last name together into a single string.
      ///
      /// Uses a simple form of string concatenation.
      /// </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;
      }
      
  46. SA1645:IncludedDocumentationFileDoesNotExist: 如果註解中包含文件,要確定這個文件存在

    • StyleCop Analyzers 預設取消此規則
  47. SA1646:IncludedDocumentationXPathDoesNotExist: 如果註解中包含文件並使用 path 時,要確定 path 正確

    • StyleCop Analyzers 預設取消此規則
  48. SA1647:IncludeNodeDoesNotContainValidFileAndPath: 如果註解中包含文件,文件與 path 都要正確

    • StyleCop Analyzers 預設取消此規則
  49. SA1648:InheritDocMustBeUsedWithInheritingClass: 說明註解 <inheritdoc> Tag 不能用在不是繼承的 class

    • 正確:

      /// <summary>
      /// Hello is Class2
      /// </summary>
      public class Class2
      {
      }
      
    • 錯誤:

      /// <summary>
      /// Hello is Class2
      /// </summary>
      /// <inheritdoc>inherit from Class1</inheritdoc>
      public class Class2
      {
      }
      
  50. SA1649:FileHeaderFileNameDocumentationMustMatchTypeName: 檔案名稱必須為第一個 class 的名稱

  51. SA1650:ElementDocumentationMustBeSpelledCorrectly: 註解不能有拼寫錯誤

    • StyleCop Analyzers 預設取消此規則
  52. SA1651:DoNotUsePlaceholderElements: 在註解中不要使用 <placeholder> Tag

  53. SA1652:EnableXmlDocumentationOutput: 在專案建置時,允許輸出並檢查 XML 說明檔案

不清楚的規則內容 (歡迎告知小弟出現情況或是否需要設定開啟)

  • SA1014:OpeningGenericBracketsMustBeSpacedCorrectly
  • SA1015:ClosingGenericBracketsMustBeSpacedCorrectly
  • SA1018:NullableTypeSymbolsMustNotBePrecededBySpace
  • SA1019:MemberAccessSymbolsMustBeSpacedCorrectly
  • SA1020:IncrementDecrementSymbolsMustBeSpacedCorrectly
  • SA1023:DereferenceAndAccessOfMustBeSpacedCorrectly
  • SA1129:DoNotUseDefaultValueTypeConstructor

[新增的規則]

StyleCop Analyzers 新增的規則

  • SA1127:GenericTypeConstraintsMustBeOnOwnLine: 泛型條件約束應該要多行顯示,不可以放在同一行
  • SA1128:ConstructorInitializerMustBeOnOwnLine: 建構函式初始化繼承時不可以放在同一行,應該要換新的一行,並以「:」開頭
  • SA1129:DoNotUseDefaultValueTypeConstructor:
  • SA1130:UseLambdaSyntax: delegate 委派的匿名方法使用 Lambda 語法 (=>)
  • SA1131:UseReadableConditions: 變數不可以出現在條件句右邊
  • SA1132:DoNotCombineFields: 不要串聯欄位宣告
  • SA1133:DoNotCombineAttributes: 一個中括號只宣告一個屬性
  • SA1134:AttributesMustNotShareLine: 不要在同一行宣告多個屬性
  • SA1216:UsingStaticDirectivesMustBePlacedAtTheCorrectLocation: using static 時應擺在一般的 using 之後和別名 using 之前
  • SA1217:UsingStaticDirectivesMustBeOrderedAlphabetically: using static 時應按照字母順序排序
  • SA1306:FieldNamesMustBeginWithLowerCaseLetter: 私有欄位的變數名稱首字母小寫
    • 和原本的 Style Cop 規則不同
  • SA1312:VariableNamesMustBeginWithLowerCaseLetter: 變數名稱首字母小寫
  • SA1313:ParameterNamesMustBeginWithLowerCaseLetter: 參數名稱首字母小寫
  • SA1412:StoreFilesAsUtf8: 檔案儲存時,儲存成 utf-8 格式
  • SA1651:DoNotUsePlaceholderElements:
  • SA1652:EnableXmlDocumentationOutput:

[參考來源]

  1. https://github.com/DotNetAnalyzers/StyleCopAnalyzers
  2. http://bradywang0416.blogspot.com/2015/03/stylecop.html
  3. https://dotblogs.com.tw/hatelove/2011/12/22/introducing-stylecop

若有謬誤,煩請告知,新手發帖請多包涵