CA1802:建議在適當時使用常值

型別名稱

UseLiteralsWhereAppropriate

CheckId

CA1802

分類

Microsoft.Performance

中斷變更

中斷

原因

欄位宣告為 static 和 readonly (在 Visual Basic 中為 Shared and ReadOnly),並以編譯時期能計算的值進行初始化。

規則描述

呼叫宣告型別的靜態建構函式 (Constructor) 時,staticreadonly 欄位的值會在執行階段進行計算。如果 staticreadonly 欄位會在宣告時進行初始化,但卻未明確地宣告靜態建構函式,則編譯器會發出一個靜態建構函式以初始化欄位。

const 欄位的值會在編譯時期進行計算,並儲存於中繼資料 (Metadata) 中,在與 staticreadonly 欄位進行比較時,會增加執行階段的效能。

因為指定給目標欄位的值可在編譯時期進行計算,所以將宣告變更為 const 欄位,其值便可於編譯時期進行計算,而不是在執行階段計算。

如何修正違規

若要修正此規則的違規情形,請以 const 修飾詞 (Modifier) 來取代 static 和 readonly 修飾詞。

隱藏警告的時機

如果效能並非考量重點,則您可以放心地隱藏這項規則的警告,或是停用該規則。

範例

下列範例會顯示違反規則的型別 (UseReadOnly) 和符合規則的型別 (UseConstant)。

Imports System

Namespace PerformanceLibrary

   ' This class violates the rule. 
   Public Class UseReadOnly

      Shared ReadOnly x As Integer = 3
      Shared ReadOnly y As Double = x + 2.1
      Shared ReadOnly s As String = "readonly" 

   End Class 

   ' This class satisfies the rule. 
   Public Class UseConstant

      Const x As Integer = 3
      Const y As Double = x + 2.1
      Const s As String = "const" 

   End Class 

End Namespace
using System;

namespace PerformanceLibrary
{
   // This class violates the rule. 
   public class UseReadOnly
   {
      static readonly int x = 3;
      static readonly double y = x + 2.1;
      static readonly string s = "readonly";
   }

   // This class satisfies the rule. 
   public class UseConstant
   {
      const int x = 3;
      const double y = x + 2.1;
      const string s = "const";
   }
}